使用CloudKit从iCloud获取公共记录

时间:2017-02-21 14:30:31

标签: ios icloud cloudkit

我有以下代码将我的资产上传到iCloud

func uploadAsset(recordType: String, fileURL: URL) {
    let record = CKRecord(recordType: recordType)
    record["file"] = CKAsset(fileURL: fileURL)

    CKContainer.default().publicCloudDatabase.save(record) { savedRecord, error in
        if let saveError = error {
            print("An error occurred in \(saveError)")
        } else {
            print(savedRecord)
        }
    }
}

这绝对有效,因为我可以进入CloudKit仪表板,实际查看记录并下载附件。

以下是从该函数输出的savedRecord示例:

Optional(<CKRecord: 0x100f27f60; recordID=F6DF33CB-35DA-483A-A5B5-33542E435689:(_defaultZone:__defaultOwner__), recordChangeTag=izfmgx06, values={
    file = "<CKAsset: 0x1703e6800; path=/private/var/mobile/Containers/Shared/AppGroup/992A6367-11F5-491F-BE37-C9E4BBA865E6/voice/1487611173.95385.m4a, size=33547, UUID=D8F70489-1FF8-4CE8-99BE-390741E8136D, signature=<01a5bd3c fd9b8042 cb52cc23 3681af91 50aacaa5 97>>";
}, recordType=Voice>
{
    creatorUserRecordID -> <CKRecordID: 0x17003ebe0; recordName=__defaultOwner__, zoneID=_defaultZone:__defaultOwner__>
    lastModifiedUserRecordID -> <CKRecordID: 0x17003e740; recordName=__defaultOwner__, zoneID=_defaultZone:__defaultOwner__>
    creationDate -> 2017-02-21 14:24:28 +0000
    modificationDate -> 2017-02-21 14:24:28 +0000
    modifiedByDevice -> 3AB140FD824827C374412EBB6B72307C57DCF1E07A7FE58F13EBF445ACCB0EA3
    file -> <CKAsset: 0x1703e6800; path=/private/var/mobile/Containers/Shared/AppGroup/992A6367-11F5-491F-BE37-C9E4BBA865E6/voice/1487611173.95385.m4a, size=33547, UUID=D8F70489-1FF8-4CE8-99BE-390741E8136D, signature=<01a5bd3c fd9b8042 cb52cc23 3681af91 50aacaa5 97>>]

我想,由于这是一个公共记录,我可以在另一个共享同一个自定义iCloud容器字符串的应用程序中下载。

但是,使用RecordIDName(在这种情况下:F6DF33CB-35DA-483A-A5B5-33542E435689),我无法获取记录。

这是我的下载代码:

    let recordId = CKRecordID(recordName: "F6DF33CB-35DA-483A-A5B5-33542E435689")


    CKContainer.default().publicCloudDatabase.fetch(withRecordID: recordId) { (results, error) -> Void in

        DispatchQueue.main.async {
            if error != nil {

                print(" Error Fetching Record  " + error!.localizedDescription)
            } else {
                if results != nil {
                    print("pulled record")

                    let record = results as CKRecord!

                    print(record)
                }
            }
        }
    }

我只是得到如下错误:

 Error Fetching Record  Error fetching record <CKRecordID: 0x10024c6f0; recordName=6988103A-E795-441B-A115-2D044872AAAC, zoneID=_defaultZone:__defaultOwner__> from server: Record not found

任何帮助表示赞赏。提前致谢! :)

1 个答案:

答案 0 :(得分:2)

错误在于使用

CKContainer.default()

在创作和拉动阶段。相反,我应该在里面使用一个指定的自定义容器,即

CKContainer(identifier: "iCloud.tech.jackrobson.myApp")