简体   繁体   中英

Cannot create a file in iOS (cocoa error 514.)

In my app I've to create a csv file, so I create this method:

+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
    NSMutableString *target = [@"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];

    for (NSDictionary *dict in promoArray) {
        [target appendFormat:@"%@,%@,%@,%@,%@,%@,%@,%@\n",dict[@"name"],dict[@"surname"],dict[@"email"],dict[@"birthdate"],dict[@"address"],dict[@"city"],dict[@"zip"],dict[@"phone"]];
    }
    NSError *error = nil;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"profiles.csv"];

    NSURL *url = [NSURL URLWithString:fileName];

    BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];

    if (!success) {
        NSLog(@"Errore: %@", error.localizedDescription);
    }
}

But when I run the app, for now it saves the .plist file but it doesn't save the .csv file. When I look at the console it tells me: Error: The operation couldn't be completed. (Cocoa error 514.) Error: The operation couldn't be completed. (Cocoa error 514.) . So I searched in the web what means error 514, I found this , in which I searched for the error and I found NSFileWriteInvalidFileNameError = 514 , how I can solve this error? In my method what's the problem. I hope you can help me to solve this issue

SOLVED BY MYSELF:

+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
    NSMutableString *target = [@"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];

    for (NSDictionary *dict in promoArray) {
        [target appendFormat:@"%@,%@,%@,%@,%@,%@,%@,%@\n",dict[@"name"],dict[@"surname"],dict[@"email"],dict[@"birthdate"],dict[@"address"],dict[@"city"],dict[@"zip"],dict[@"phone"]];
    }
    NSError *error = nil;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"profiles.csv"];

    BOOL success = [target writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];

    if (!success) {
        NSLog(@"Errore: %@", error.localizedDescription);
    }
}

Change this line

BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];

to

BOOL success = [target writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM