Some notes on working with iCloud (Xcode)

Apple's iCloud Fundamentals guide and Matt Neuburg's Programming iOS 7 will get you well on your way to using iCloud.

There are some important things to note, however, especially if you are using Programming iOS 7:
  1. The NSFileManager method URLForUbiquityContainerIdentifier: will return the URL for the iCloud container, but if you want the files you save to be visible in System Preferences on OS X, for example, then save them to the Documents subdirectory.
  2. If you are using Neuburg's book and want to modify the code to obtain a URL to the Documents subdirectory, then after you've got you NSURL named ubiq, add a new property to the app delegate called ubiqdocs and use the following code: self.ubiqdocs = [ubiq URLByAppendingPathComponent:@"Documents" isDirectory:YES]; You can then use this whenever you want files to be visible and ubiq when you want them to be invisible.
  3. Files saved to the address of a current file will not be written and instead generate an error. URLs must point to non-existent files, after a file is initially written to iCloud you must then use the NSFileCoordinator class.
  4. When using the NSFileManager method isUbiquitousItemAtURL:URLWithString:relativeToURL: the file at the URLWithString will automatically be deleted from its original location when sent to iCloud.
  5. Take note of Apple's warning below about isUbiquitousItemAtURL:URLWithString:relativeToURL: 
"Important: Avoid calling this method from your app’s main thread. This method performs a coordinated write operation on the specified file, which can block for a long time. Additionally, if the file presenter that is monitoring the file is incorrectly configured so that it receives messages on the main operation queue, calling this method on the main thread can cause a deadlock. Instead, use a dispatch queue to call this method from background thread. After the method returns, message your main thread to update the rest of your app’s data structures." (cf. Grand Central Dispatch)

Some of this you don't need to worry about too much because UIDocumentNSUbiquitousKeyValueStore and CoreData handle most of it, but it is always nice to be able to see iCloud file storage working in its most basic form before entering into UIDocument and the other classes.

Endorse on Coderwall

Comments