The easiest way to write NSData to a file
Solution 1:
NSData
has a method called writeToURL:atomically:
that does exactly what you want to do. Look in the documentation for NSData
to see how to use it.
Solution 2:
Notice that writing NSData
into a file is an IO operation that may block the main thread. Especially if the data object is large.
Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:
// Use GCD's background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"yourfilename.dat"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
Solution 3:
writeToURL:atomically: or writeToFile:atomically: if you have a filename instead of a URL.
Solution 4:
You also have writeToFile:options:error:
or writeToURL:options:error:
which can report error codes in case the saving of the NSData
failed for any reason. For example:
NSError *error;
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
if (!folder) {
NSLog(@"%s: %@", __FUNCTION__, error); // handle error however you would like
return;
}
NSURL *fileURL = [folder URLByAppendingPathComponent:filename];
BOOL success = [data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(@"%s: %@", __FUNCTION__, error); // handle error however you would like
return;
}