user346443
user346443

Reputation: 4852

NSData writeToFile not working

I cant seem to get nsdata to write to a file. Any ideas what i may be doing wrong. Thanks in advance.

NSString* filename = @"myfile.txt";

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:filename];    

if ([fileManager fileExistsAtPath:applicationDocumentsDir])
    NSLog(@"applicationDocumentsDir exists");   // verifies directory exist

NSData *data = [NSData dataWithContentsOfURL:URL];

if (data) {    
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

I keep getting the error

"The operation couldn’t be completed. No such file or directory"

Upvotes: 11

Views: 29980

Answers (2)

Jeff
Jeff

Reputation: 2699

To get more information, you can use

writeToFile:options:error:

instead of

writeToFile:atomically:

but you need to create all the subdirectories in the path prior to doing the write. Like this:

// if the directory does not exist, create it...
if ( [fileManager fileExistsAtPath:dir_path] == NO ) {
    if ( [fileManager createDirectoryAtPath:dir_path withIntermediateDirectories:NO attributes:NULL error:&error] == NO  ) {
        NSLog(@"createDirectoryAtPath failed %@", error);
    }
}

Upvotes: 0

user704010
user704010

Reputation:

Try

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"myfile.txt"];

And

 if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
        NSLog(@"applicationDocumentsDir exists");   

Upvotes: 5

Related Questions