NSData writeToFile not working

user346443 picture user346443 · Aug 29, 2011 · Viewed 28.9k times · Source

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"

Answer

user704010 picture user704010 · Aug 29, 2011

Try

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

And

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