I’m trying to copy a file from my iCloud container to my apps’ cache directory. I keep getting The operation couldn’t be completed. (Cocoa error 512.) in my log, which is a very broad error meaning NSFileWriteUnknownError, or the write failed and iOS doesn’t know why.
Here is the code for when the NSMetadataQuery finishes and has the file names in iCloud. I’ll briefly describe the code below.
- (void)loadData:(NSMetadataQuery *)query {
NSArray *cache = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[cacheDirectory stringByAppendingString:@"/issues"] error:NULL];
for (NSMetadataItem *item in [query results]) {
NSURL *name = [item valueForAttribute:NSMetadataItemURLKey];
NSString *nameString = [item valueForAttribute:NSMetadataItemPathKey];
NSError *error;
NSURL *cacheURL = [NSURL fileURLWithPath:cacheDirectory];
NSURL *destination = [cacheURL URLByAppendingPathComponent:[NSString stringWithFormat:@"issues/%@", [[nameString stringByDeletingLastPathComponent] lastPathComponent]] isDirectory:YES];
[[NSFileManager defaultManager] copyItemAtURL:[name URLByDeletingLastPathComponent] toURL:destination error:&error];
}
}
}
This app syncs newspaper issues. In the iCloud documents container, there are folders with the data (one folder could be 5.1.12), and inside each folder is a PDF file with the same name (5.1.12.pdf).
Any idea why this is happening? Thanks for your help.
iCloud: file://localhost/private/var/mobile/Library/Mobile%20Documents/AppBundleID/Documents/5.3.12/
Local: file://localhost/var/mobile/Applications/F91E115B-ECED-403E-AB61-41F7A99EF928/Library/Caches/issues/5.3.12/
When iCloud syncs a file to an iOS device, it will first create an empty, dataless file in your app’s container to let you know there is a file available. This is what your
NSMetadataQueryreports.If you look at the other keys of your
NSMetadataItem, you’ll probably notice it says your item is not downloaded yet.Before being able to copy that file or to open it, you have to ask iCloud to download it. Taking a coordinated read at the item’s path (as you should do around any opening or copying operation) will implicitly download the file.