NSKeyedArchiver 和 iCloud

NSKeyedArchiver and iCloud

现在在我的应用程序中,我有一个顶级对象,它带有一个 -(void)archive 方法,它将自身归档到应用程序的文档目录中。

我想知道是否可以通过更改文件路径将存档简单地保存到 iCloud 而不是本地。

我已经阅读了很多关于使用 iCloud 的文章,但我还没有看到这个问题得到解决。我猜这是不可能的,但我想确定一下。

谢谢。

您不应将文件直接保存到 iCloud,而应将其保存在本地,然后将其移动到与您的应用关联的 iCloud 文件夹。

首先您需要查看 file coordination 您应该使用它来将文件保存到 iCloud。

然后您只需检索要保存的文件的 URL 或路径。您可以通过调用以下方式获取您的 iCloud 目录:[[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"myIdentifier"]; 然后附加适当的路径组件。

最后,您将文件 (e.g.myFile.dat) 保存到临时本地文件夹,例如应用程序的文档目录,然后调用:[[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:/*local URL*/ destinationURL:/*Cloud URL*/ error:&error]; 这会将文件从本地文件夹移动到 iCloud 文件夹,然后然后 OS' 同步守护程序完成剩下的工作。

如果您保存到 iCloud 文档目录,您的文件将通过 iCloud 驱动器对用户可见。如果您保存到不同的 iCloud 目录,用户将无法看到该文件。

注意:您需要使用 NSMetadataQuery to discover files saved to iCloud by another device. Also iOS devices do not automatically download files that you save to iCloud; you need to specifically call [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error]; to initiate a download. OS X devices will automatically download iCloud files. You can use the NSFilePresenter 协议来监视应用程序生命周期内 iCloud 目录的变化(以检测其他设备保存的文件)。