iosiphonefilensbundle

Write a file on iOS


How do I write a file on iOS? I'm trying to do it with the following code but I'm doing something wrong:

char *saves = "abcd";
NSData *data = [[NSData alloc] initWithBytes:saves length:4]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];
[data writeToFile:appFile atomically:YES];

I have created MyFile.txt on resources.


Solution

  • Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

    NSLog(@"%@",documentsDirectory);
    

    and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file