Created
September 20, 2012 09:52
-
-
Save eternalstorms/3754995 to your computer and use it in GitHub Desktop.
iCloud file sync step by step
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1) Turn on iCloud in your entitlements. In Xcode, you can find 'em in your target, under the Summary tab, at the bottom. Turn on 'Enable Entitlements' and press + on the iCloud Containers list. | |
2) You get a folder. Stuff in it gets synchronized around. This is the easy part. You can use the -[NSFileManager URLForUbiquityContainerIdentifier:] call to find out where the container is. | |
Extra notes: The identifier is whatever name Xcode added to the list in step 1. Make sure you call this at least once, because calling this turns on all the iCloud stuff in Foundation. If iCloud is turned off, this will return nil. | |
3) This folder is organized like a home folder. Yep, this means this one can have a Documents folder, a Library, whatever. You have to create those folders if you want to use them. | |
4) Looking at the folder directly is not useful. (Some of the files may not have sync'd yet, so they're not yet in the folder.) Use NSMetadataQuery. This will give you all files, including those not downloaded yet. | |
To search iCloud, use a .searchScope of NSMetadataQueryUbiquitousDocumentsScope and/or NSMetadataQueryUbiquitousDataScope (one looks in Documents inside the iCloud folder, the other everywhere else.) | |
5) Whenever you want to do anything to a file in the iCloud directory, you must make a NSFileCoordinator and call the right method and make sure all the reading/writing happens in the blocks you pass. This will make sure you and the iCloud sync daemon can dance the sweet, sweet sync tango. | |
If you don't have a file presenter for that file, just pass nil to the initWithFilePresenter: thing. It won't mind. | |
6) If you need to keep a file open, make sure to make a NSFilePresenter for it and add it via +[NSFileCoordinator addFilePresenter:]. Remove it when you close it. This object will get messages if iCloud needs to sync stuff in an open file. You can build your app around NSDocument (Mac) or UIDocument (iOS) to simplify this — they're file presenters and they add and remove by themselves as they open or close. | |
7) If you try to open a not-downloaded file, NSFileCoordinator will block the thread until it arrives (ew!). You can avoid that by asking NSFileManager to download the file via -[NSFileManager startDownloadingUbiquitousItemAtURL:error:]. You get progress reports via the 'ubiquity' attributes of the NSMetadataItem the NSMetadataQuery gave you. | |
(source: http://infinite-labs.net/bp/#icloud) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment