2
votes

One can sync files to iCloud by just creating files in the ubiquity container like this:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *containerURL = [fileManager URLForUbiquityContainerIdentifier:nil];
NSURL *dirURL = [containerURL URLByAppendingPathComponent:@"files" isDirectory:YES];

NSError *error;
[fileManager createDirectoryAtURL:dirURL withIntermediateDirectories:NO attributes:nil error:&error];

NSURL *icloudURL = [dirURL URLByAppendingPathComponent:@"somefile.txt"];
[fileManager createFileAtPath:[icloudURL path] contents:someData attributes:nil];

This works and seems to be a simple and straightforward way to put files into iCloud and yet I couldn't find such examples in the documentation or hints that such API usage is allowed. Yielding the questions: Is this safe? Is this allowed by Apple API documentation somewhere? Does it have any known problems?

Remarks:

  • I am looking for the simplest possible way to manage a bunch of unrelated files in iCloud.
  • The given approach is simpler to the setUbiquitous:itemAtURL:destinationURL:error:-method because it allows persisting files ad-hoc from NSData without creating a temporary file in the app sandbox and it overwrites existing files without extra checking for that case.
  • The setUbiquitos-API doc says "Your app must have an active file presenter object configured to monitor the specified file or directory before calling this method." and the iCloud design guide says "Always use a file coordinator to access an iCloud file or file package.". Which makes me worry if the given code is problematic.
  • I see the need for FileCoordinator/FilePresenter when the consistency of many files f.e. in a bundle directory needs to be maintained. But this seems too much overhead if you just want to manage a bunch of independent files in the cloud. Especially given the nature of this API.
  • I considered using UIDocument: Treating the folder as a document doesn't feel like a good fit given the load/store-everything-at-once-approach of the class. Treating each file as a document feels ok but quite cumbersome.
1

1 Answers

0
votes

There is one thing I'm sure that working with iCloud is not simple!

There is too many exceptions that I thought they never occurred but they still occurred. (e.g: sometime iCloud sent to my app an NSConcreteData object but my app used NSFileWrapper; sometime my file became a folder and after some minutes it cameback a files)

There are many way to access iCloud. This is an easy way: http://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1

Remember be always careful when working with iCloud (everything can happen)

Good luck