如何编写将iOS中的文件从沙箱复制到iCloud容器的代码?

时间:2018-09-17 09:08:38

标签: ios icloud nsfilecoordinator nsfilepresenter

我注意到在Apple的ShapeEdit示例中,将文件模板复制到iCloud容器的代码不使用文件演示器,但是它使用了NSFileCordinator。这是为什么?我认为使用iCloud进行任何文件操作都需要使用bot NSFileCoordinator和使用NSFilePresenter协议的对象。我还注意到,他们使用copyItem代替了setUbiquitous,就像我认为的那样。

如果此代码不正确,我应该如何编写正确的代码?

fileprivate func createNewDocumentWithTemplate(_ templateURL: URL) {
    /*
        We don't create a new document on the main queue because the call to
        fileManager.URLForUbiquityContainerIdentifier could potentially block
    */
    coordinationQueue.addOperation {
        let fileManager = FileManager()
        guard let baseURL = fileManager.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("Untitled") else {

            self.presentCloudDisabledAlert()

            return
        }

        var target = baseURL.appendingPathExtension(DocumentBrowserController.documentExtension)

        /*
            We will append this value to our name until we find a path that
            doesn't exist.
        */
        var nameSuffix = 2

        /*
            Find a suitable filename that doesn't already exist on disk.
            Do not use `fileManager.fileExistsAtPath(target.path!)` because
            the document might not have downloaded yet.
        */
        while (target as NSURL).checkPromisedItemIsReachableAndReturnError(nil) {
            target = URL(fileURLWithPath: baseURL.path + "-\(nameSuffix).\(DocumentBrowserController.documentExtension)")

            nameSuffix += 1
        }

        // Coordinate reading on the source path and writing on the destination path to copy.
        let readIntent = NSFileAccessIntent.readingIntent(with: templateURL, options: [])

        let writeIntent = NSFileAccessIntent.writingIntent(with: target, options: .forReplacing)

        NSFileCoordinator().coordinate(with: [readIntent, writeIntent], queue: self.coordinationQueue) { error in
            if error != nil {
                return
            }

            do {
                try fileManager.copyItem(at: readIntent.url, to: writeIntent.url)

                try (writeIntent.url as NSURL).setResourceValue(true, forKey: URLResourceKey.hasHiddenExtensionKey)

                OperationQueue.main.addOperation {
                    self.openDocumentAtURL(writeIntent.url)
                }
            }
            catch {
                fatalError("Unexpected error during trivial file operations: \(error)")
            }
        }
    }
}

0 个答案:

没有答案