icloud UIDocument 文件同步学习小结

UIDocument

  1. 如何使用icloud 同步文件
  2. 如何添加文件到icloud
  3. 如何获取icloud中文件列表
  4. 如何删除icloud中文件
  5. 多个设备同时打开一个document 如何同步
  6. 多个设备如何同步document列表
  7. 如何处理冲突

1. 基本配置

首先添加icloud capability,这个需要开发者账号, 然后添加一个icloud container id。

2. 添加数据

想把一个文件数据放到icloud上,要先检查icloud 是否可用

  1. 检查icloud是否已经可用,并获取到icloud container url
  guard FileManager.default.ubiquityIdentityToken != nil else {
            print("⛔️ iCloud isn't enabled yet. Please enable iCloud and run again.")
            return nil
        }
        
        // Dispatch to a global queue because url(forUbiquityContainerIdentifier:) might take a nontrivial
        // amount of time to set up iCloud and return the requested URL
        //
        DispatchQueue.global().async {
            if let url = FileManager.default.url(forUbiquityContainerIdentifier: containerIdentifier) {
                DispatchQueue.main.async {
                    self.containerRootURL = url
                }
                return
            }
            print("⛔️ Failed to retrieve iCloud container URL for:\(containerIdentifier ?? "nil")\n"
                    + "Make sure your iCloud is available and run again.")
        }

上面代码检查icloud 功能是否开启,并获取icloud container 容器的url 地址。

  1. 下面要封装数据,然后放到icloud container里面
    需要自定义类继承UIDocument,然后通过操作document来实现文件的增删改
   let document = Document(fileURL: fileURL)
        document.save(to: fileURL, for: .forCreating) { _ in
            document.close { success in
                if !success {
                    print("Failed to close the document: \(fileURL)")
                }
                completionHandler?(success)
            }
        }


  func removeDocument(at fileURL: URL) {
        DispatchQueue.global().async {
            NSFileCoordinator().coordinate(writingItemAt: fileURL, options: .forDeleting, error: nil) { newURL in
                do {
                    try FileManager.default.removeItem(atPath: newURL.path)
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }
        }
    }

要看看文件是否已经添加成功,可以在设置->iCloud->存储空间,
但是要配置一些数据

 <key>NSUbiquitousContainers</key>
    <dict>
        <key>iCloud.com.example.apple-samplecode.SimpleiCloudDocument</key>
        <dict>
            <key>NSUbiquitousContainerIsDocumentScopePublic</key> // 是否支持在File app中查看
            <true/>
            <key>NSUbiquitousContainerName</key> // 在File app中显示的名称
            <string>SimpleiCloudDocument</string>
            <key>NSUbiquitousContainerSupportedFolderLevels</key>
            <string>ANY</string>
        </dict>
    </dict>

要实现在File app查看自己app中数据,并实现点击自定义格式文件能打开app,要实现配置CFBundleDocumentTypes and UTExportedTypeDeclarations
设置LSSupportsOpeningDocumentsInPlace = true
实现scene(_:openURLContexts:) 方法 具体配置看demo

<key>UTExportedTypeDeclarations</key>
    <array>
        <dict>
            <key>UTTypeConformsTo</key>
            <array>
                <string>com.apple.package</string>
                <string>public.content</string>
                <string>public.data</string>
            </array>
            <key>UTTypeDescription</key>
            <string>AIScanner</string>
            <key>UTTypeIconFiles</key>
            <string>Icon.png</string>
            <key>UTTypeIdentifier</key>
            <string>com.daping.pdfdoc.icloud.aisc</string>
            <key>UTTypeTagSpecification</key>
            <dict>
                <key>public.filename-extension</key>
                <array>
                    <string>aisc</string>
                </array>
                <key>public.mime-type</key>
                <string>application/aisc</string>
            </dict>
        </dict>
    </array>
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeIconFiles</key>
            <array/>
            <key>CFBundleTypeName</key>
            <string>AIScanner</string>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>LSHandlerRank</key>
            <string>Owner</string>
            <key>LSTypeIsPackage</key>
            <true/>
            <key>LSItemContentTypes</key>
            <array>
                <string>com.daping.pdfdoc.icloud.aisc</string>
            </array>
        </dict>
    </array>
    <key>NSUbiquitousContainers</key>
    <dict>
        <key>iCloud.com.danping.pdfdoc.aiscanner</key>
        <dict>
            <key>NSUbiquitousContainerIsDocumentScopePublic</key>
            <true/>
            <key>NSUbiquitousContainerName</key>
            <string>SimpleiCloudDocument</string>
            <key>NSUbiquitousContainerSupportedFolderLevels</key>
            <string>ANY</string>
        </dict>
    </dict>
    <key>LSSupportsOpeningDocumentsInPlace</key>
    <true/>

3. 查询数据

如何查询icloud document
当在一个设备添加了document, icloud并不会立即把数据同步到其他设备,而是先同步metadata,因为metadata 数据量小,根据不同设置选择是否立即同步数据,iOS设备不会立即同步,mac会立即同步。
其他设置收到icloud 新数据通知后,数据并没有同步过来,所有不能使用FileManager API 去操作数据。
要查询和监听icloud 数据变换要使用 NSMetadataQuery 接口。

metadataQuery.notificationBatchingInterval = 1
metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDataScope, NSMetadataQueryUbiquitousDocumentsScope]
metadataQuery.predicate = NSPredicate(format: "%K LIKE %@", NSMetadataItemFSNameKey, "*." + Document.extensionName)
metadataQuery.sortDescriptors = [NSSortDescriptor(key: NSMetadataItemFSNameKey, ascending: true)]
metadataQuery.start()

当读取数据的时候,为了避免冲突,先关闭查询接口,然后再开启。

func metadataItemList() -> [MetadataItem] {
    var result = [MetadataItem]()
    metadataQuery.disableUpdates()
    if let metadatItems = metadataQuery.results as? [NSMetadataItem] {
        result = metadataItemList(from: metadatItems)
    }
    metadataQuery.enableUpdates()
    return result
}

4. 冲突解决

icloud 多个设备之前同步数据,不同的网络环境,冲突不可避免。比如多个设备都断网,然后同时修改数据,再同时打开网络, 就会出现冲突。

  @objc
    func documentStateChanged(_ notification: Notification) {
        guard let document = document else { return }
        printDocumentState(for: document)
        
        // The document state is normal.
        // Update the UI with unpresented peer changes, if any.
        //
        if document.documentState == .normal {
            navigationItem.rightBarButtonItem?.isEnabled = true
            handleConflictsItem.isEnabled = false
            if !document.unpresentedPeerChanges.isEmpty {
                let changes = document.unpresentedPeerChanges
                document.clearUnpresentedPeerChanges()
                updateCollectionView(with: changes)
            }
            return
        }
        // The document has conflicts but no error.
        // Update the UI with unpresented peer changes if any.
        //
        if document.documentState == .inConflict {
            navigationItem.rightBarButtonItem?.isEnabled = true
            handleConflictsItem.isEnabled = true
            if !document.unpresentedPeerChanges.isEmpty {
                let changes = document.unpresentedPeerChanges
                document.clearUnpresentedPeerChanges()
                updateCollectionView(with: changes)
            }
            return
        }
        // The document is in a closed state with no error. Clear the UI.
        //
        if document.documentState == .closed {
            navigationItem.rightBarButtonItem?.isEnabled = false
            handleConflictsItem.isEnabled = false
            title = ""
            var snapshot = DiffableImageSourceSnapshot()
            snapshot.appendSections([0])
            diffableImageSource.apply(snapshot)
            return
        }
        // The document has conflicts. Enable the toolbar item.
        //
        if document.documentState.contains(.inConflict) {
            handleConflictsItem.isEnabled = true
        }
        // The document is editingDisabled. Disable the UI for editing.
        //
        if document.documentState.contains(.editingDisabled) {
            navigationItem.rightBarButtonItem?.isEnabled = false
            handleConflictsItem.isEnabled = false
        }
    }

上面代码显示 当打开一个document后,可以监听document的变化,包括冲突
不过解决冲突很简单的,Document 监听状态变化,当检测到冲突的时候,根据不同策略去解决,比如再简单的根据修改时间,最新的保留,其他的删除。

  private func resolveConflictsAsynchronously(document: Document, completionHandler: ((Bool) -> Void)?) {
        DispatchQueue.global().async {
            NSFileCoordinator().coordinate(writingItemAt: document.fileURL,
                                           options: .contentIndependentMetadataOnly, error: nil) { newURL in
                let shouldRevert = self.pickLatestVersion(for: newURL)
                completionHandler?(shouldRevert)
            }
        }
    
    }

 private func pickLatestVersion(for documentURL: URL) -> Bool {
        guard let versionsInConflict = NSFileVersion.unresolvedConflictVersionsOfItem(at: documentURL),
              let currentVersion = NSFileVersion.currentVersionOfItem(at: documentURL) else {
            return false
        }
        var shouldRevert = false
        var winner = currentVersion
        for version in versionsInConflict {
            if let date1 = version.modificationDate, let date2 = winner.modificationDate,
               date1 > date2 {
                winner = version
            }
        }
        if winner != currentVersion {
            do {
                try winner.replaceItem(at: documentURL)
                shouldRevert = true
            } catch {
                print("Failed to replace version: \(error)")
            }
        }
        do {
            try NSFileVersion.removeOtherVersionsOfItem(at: documentURL)
        } catch {
            print("Failed to remove other versions: \(error)")
        }
        return shouldRevert
    }

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,367评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,959评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,750评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,226评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,252评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,975评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,592评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,497评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,027评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,147评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,274评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,953评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,623评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,143评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,260评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,607评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,271评论 2 358

推荐阅读更多精彩内容