2

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.
4

1 回答 1

0

有一件事我确信使用 iCloud 并不简单!

有太多的例外,我认为它们从未发生过,但它们仍然发生。(例如:有时 iCloud 向我的应用程序发送了一个NSConcreteData对象,但我的应用程序使用NSFileWrapper了;有时我的文件变成了一个文件夹,几分钟后它又返回了一个文件)

有很多方法可以访问 iCloud。这是一个简单的方法: http ://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1

记住在使用 iCloud 时要小心(任何事情都有可能发生)

祝你好运

于 2013-06-14T04:37:38.137 回答