I am trying to write to the following path:
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *storePath = [docDir stringByAppendingPathComponent:@"/newfolder/test.jpg"];
NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
BOOL saved = [data writeToFile:storePath atomically:NO];
NSLog(@"%c", saved);
Now, nothing gets printed and I can't see the file in my simulator. Is it because "newfolder" folder within the Documents main folder is not created yet. If so, is there a way to create it if it is not there yet?
Thanks!
Yes, you must make sure the folder is created first. Use NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:
passing in the path to the folder you wish to create (not the file you are trying to write).
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *storePath = [docDir stringByAppendingPathComponent:@"newfolder/test.jpg"];
[[NSFileManager defaultManager] createDirectoryAtPath:[storePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
You should check the return value of these methods and handle any failures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With