NSKeyedArchiver and iCloud

471 Views Asked by At

Right now in my application I have a top level object with an -(void)archive method that will archive itself to the application's documents directory.

I'm wondering if it's possible to simply save the archive to iCloud rather than locally, by changing the file path.

I've read quite a bit on using iCloud, but I haven't seen this question addressed. I'm guessing it is not possible, but I want to know for sure.

Thank you.

1

There are 1 best solutions below

8
On BEST ANSWER

You shouldn't save a file directly to iCloud but save it locally and then move it to the iCloud folder associated with your app.

First you need to look at file coordination which you should use to save a file to iCloud.

Then you simply retrieve the URL or path for the file you want to save. You get your iCloud directory by calling: [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"myIdentifier"]; Then append the appropriate path components.

Finally you save the file (e.g.myFile.dat) to a temporary local folder like the Application's documents directory and then call: [[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:/*local URL*/ destinationURL:/*Cloud URL*/ error:&error]; This will move the file from the local folder to the iCloud folder and then the OS' syncing daemon does the rest.

If you save into the iCloud documents directory, your file will be visible to the user via iCloud drive. If you save into a different iCloud directory, the user will not be able to see the file.

NOTE: you need to use NSMetadataQuery to discover files saved to iCloud by another device. Also iOS devices do not automatically download files that you save to iCloud; you need to specifically call [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error]; to initiate a download. OS X devices will automatically download iCloud files. You can use the NSFilePresenter protocol to watch for changes to your iCloud directory during your app's lifetime (to detect files saved by another device).