Writing a csv from app, Cocoa error 513

时间:2015-06-30 19:20:48

标签: ios cocoa-touch csv nsarray

I am creating an iPhone app that writes to a CSV file. It seems the most simple method of this would be to add to an NSMutableString from an array. The code I have should be working expect I keep getting Cocoa error 513

The code is:

NSArray *firstArray=[NSArray arrayWithObjects:@"A",@"b",nil];
NSMutableString *csv = [NSMutableString stringWithString:@"Strings"];

NSUInteger count = [firstArray count];
for (NSUInteger i=0; i<count; i++ ) {
    [csv appendFormat:@"\n %@",
     [firstArray objectAtIndex:i]
     ];
}

NSString *yourFileName = @"leads.csv";
NSError *error;
BOOL res = [csv writeToFile:yourFileName atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (!res) {
    NSLog(@"Error %@ while writing to file %@", [error localizedDescription], yourFileName );
}

Thank you so much!

1 个答案:

答案 0 :(得分:1)

很可能是因为您正在写入您无权编写的文件位置。

Cocoa error 513转换为错误NSFileWriteNoPermissionError。

通常,当有人尝试写入应用程序包中的文件时会发生这种情况。您无法修改已编译应用程序的软件包文件夹的内容。这是因为bundle是一个已签名的编译应用程序。

当您最终通过iTunes App Store分发应用程序时,该应用程序具有验证应用程序内容的数字签名。此签名是在编译时生成的,一旦签名,Apple不希望任何人篡改内容。

确保使用以下内容写入适当的位置,例如DocumentsTempCache

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"subFolder"];
NSString *filePath = [dataPath stringByAppendingPathComponent:@"fileName.csv"];


if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
}

BOOL res = [csv writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (!res) {
    NSLog(@"Error %@ while writing to file %@", [error localizedDescription], yourFileName );
}

这些文件夹只能供您的应用访问。没有其他应用可以访问这些文件夹的内容。 (同样,您的应用无法访问其他应用的文件夹。)