将CSV文件保存到文档目录文件夹

时间:2015-07-15 22:32:09

标签: ios objective-c csv nsdocumentdirectory

我正在编写一个注册应用程序,它应该将CSV文件保存在文档目录文件夹中。我想查看输出,看看在excel中打开CSV文件时会发生什么。我使用以下代码片段找到了应该保存的位置,导航到文档目录文件夹:

NSLog(@"Info Saved");
NSLog(@"Documents Directory: %@", [[[NSFileManager defaultManager]
                                    URLsForDirectory:NSDocumentDirectory
                                    inDomains:NSUserDomainMask] lastObject]);

以下是我的代码,用于保存注册表单中11个文本字段的信息:

- (IBAction)saveFormButton:(id)sender {

// saves text field data in comma separated CSV file format
NSString *formData = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@\n",
                      self.nameTextfield.text, self.emailTextfield.text,
                      self.phoneTextfield.text, self.termTextfield.text,
                      self.schoolTextfield.text, self.graduationTextfield.text,
                      self.gpaTextfield.text, self.degreeTextfield.text,
                      self.interestTextfield.text, self.groupTextfield.text,
                      self.appliedTextfield.text];

// get document directory path
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                    NSUserDomainMask, YES)objectAtIndex:0];

// append results.csv onto doc path
NSString *event = [documentDirectoryPath stringByAppendingString:@"results.csv"];

// creates folder if it does not exist
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
    [[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}


NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

我是否应该在导航到的特定文件夹中看到一个文件?

感谢您的帮助,

2 个答案:

答案 0 :(得分:3)

更改此行:

NSString *event = [documentDirectoryPath stringByAppendingString:@"results.csv"];

为:

NSString *event = [documentDirectoryPath stringByAppendingPathComponent:@"results.csv"];

这可确保路径格式正确。此外,您似乎正在检查是否" documentDirectoryPath"在创建文件而不是文件名本身之前存在。变化:

if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
    [[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}

为:

if (![[NSFileManager defaultManager] fileExistsAtPath:event]) {
    [[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}

答案 1 :(得分:2)

这是一种更优雅的方式,代码更少

 // Content of file
 NSString* str= @"str,hey,so,good";

 // Writing    
 NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:@"file.csv"];
 [str writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];

 // Reading
 NSString *string = [[NSString alloc] initWithContentsOfFile:root encoding:NSUTF8StringEncoding error:nil];

 NSLog(@"%@",string);

结果:

2015-07-15 15:52:56.267 ObjC[2927:15828] str,hey,so,good