There isn't really a way around using UIDocument. I tried to do it in one of my first uses of iCloud, but it turned out to be a disaster without UIDocument. Using UIDocument at first seems like a lot of extra work, but it isn't.
You can easily subclass UIDocument in under an hour and get it to work with any type of file (just set the content
property as NSData). It also provides numerous benefits over the standard file system:
- Change tracking
- File conflict resolution
- Document state support
- Enhanced save / open / close features
Honestly, spending just an hour or two reading over the Apple documentation and then using it is well worth the time and brain power. A good starter article on iCloud Document storage can be found in Apple's Developer Documentation.
I have written a UIDocument subclass that will work with any type of file (NSData specifically). You can view, download, and modify the code for the UIDocument subclass on GitHub.
Create the document:
// Initialize a document with a valid file path
iCloudDocument *document = [[iCloudDocument alloc] initWithFileURL:fileURL];
// Set the content of the document
document.contents = content;
// Increment the change count
[document updateChangeCount:UIDocumentChangeDone];
Save an existing document:
// Save and close the document
[document closeWithCompletionHandler:nil];
Save a new document:
[document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:nil];
You can also sync all files stored within iCloud by using NSMetadataQuery. Apple provides a very nice example of using NSMetadata query to sync app files. Also make sure to check for iCloud before performing these operations (hint: use the ubiquityIdentityToken
method on NSFileManager).
You may also want to consider using an open-source library such as iCloud Document Sync. The iCloud Document Sync project makes it very easy to store and sync app files:
Integrate iCloud into iOS document projects with one-line code methods. Sync, upload, manage, and remove documents from iCloud quickly and easily. Helps to make iCloud "just work" for developers too.
In almost every iCloud Document Sync method, all you have to do is pass in your file data as a parameter and then it handles the rest (saving, syncing, etc.).
DISCLAIMER: I am a contributing developer to the open-source project, iCloud Document Sync. However, I believe that this project will be beneficial to you, and is relevant to this question. This is not a promotion or advertisement.