Elaborating on @cescofry's answer a bit here regarding iWork files (.pages, .numbers, .key) so others won't have to rediscover the issue. (This will work for non iWork files as well.)
If you are pulling iWork files from iCloud, you need to worry about two primary things before you can get a valid NSData object. A) Security scope through a NSFileCoordinator object (as covered by @cescofry) and B) that iWork files are actually directories/bundles not single files. The options
parameter you want for coordinateReadingItemAtURL:
is NSFileCoordinatorReadingForUploading
. This will read in single files as if you had used 0
, but will turn directories into zip files automatically. Strip off the .zip
that is added on and you'll have a valid Pages/Numbers/Keynote file. (It's valid with it on too.)
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent];
NSString *fileExtension = [newURL pathExtension];
if([fileExtension isEqualToString:@"zip"]) {
if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:@"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:@"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:@"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;
fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do something with the file data here
}
[url stopAccessingSecurityScopedResource];
Relevant Apple documentation on the NSFileCoordinator options here:
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSFileCoordinator_class/#//apple_ref/c/tdef/NSFileCoordinatorReadingOptions