因此,在我的应用程序的第一个视图控制器中,我试图创建一个包含字符串的 csv 文件,但由于某种原因它不起作用。我使用以下代码:
-(IBAction)initialButton:(id)sender {
NSLog(@"initialButton clicked");
if([securityCode.text length] == 8){
NSString *securtityCodeData = [NSString stringWithFormat:@"%@",
self.securityCode.text];
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *securityCodes=[docPath stringByAppendingPathComponent:@"securityCodes.txt"];
if (![[NSFileManager defaultManager] fileExistsAtPath:securityCodes]){
[[NSFileManager defaultManager]createFileAtPath:securityCodes contents:nil attributes:nil];
}
NSFileHandle *fileHandel = [NSFileHandle fileHandleForUpdatingAtPath:securityCodes];
[fileHandel seekToEndOfFile];
[fileHandel writeData:[securtityCodeData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandel closeFile];
NSLog(@"security code has been saved\nSecurity code:%@",securtityCodeData);
NewTrackTraceViewController *newTrackTraceViewController = [[NewTrackTraceViewController alloc]init];
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
[appDelegate.transitionController transitionToViewController:newTrackTraceViewController withOptions:UIViewAnimationOptionTransitionCrossDissolve];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[WCAlertView showAlertWithTitle:@"Security code is not valid"
message:@"Please enter a valid securitycode to continue."
customizationBlock:^(WCAlertView *alertView) {
alertView.style = WCAlertViewStyleVioletHatched;
} completionBlock:^(NSUInteger buttonIndex, WCAlertView *alertView) {
} cancelButtonTitle:@"Cancel" otherButtonTitles:@"Okay",nil];
}
}
然后我们推送到我的第二个视图控制器,在那里我想读取 csv 文件并将其内容放在标签中:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *securityCodes=[docPath stringByAppendingPathComponent:@"securityCodes.csv"];
if([[NSFileManager defaultManager] fileExistsAtPath:securityCodes]){
securityCodeLabel.text = securityCodes;
NSFileHandle *fileHandel = [NSFileHandle fileHandleForReadingAtPath:securityCodes];
NSString *securityCodeData=[[NSString alloc]initWithData:[fileHandel availableData] encoding:NSUTF8StringEncoding];
[fileHandel closeFile];
self.securityCodeLabel.text=securityCodeData;
NSLog(@"%@",securityCodeData);
}else{
NSLog(@"File does not exist");
self.securityCodeLabel.text=@"No security code found!";
}
}
我做错了什么?由于某种原因,该文件未保存..