解析CloudKit错误(CKError)

时间:2018-07-05 15:41:06

标签: ios swift cloudkit ckerror

我正在使用CloudKit,正在检查是否已创建特定区域。

在此示例中,假设未设置区域,因此CloudKit向我检索了CKError

CKError具有名为partialErrorsByItemID的属性,类型为[AnyHashable : Error]?

代码如下:

fileprivate func checkIfZonesWereCreated() {
    let privateDB = CKContainer.default().privateCloudDatabase
    let op = CKFetchRecordZonesOperation(recordZoneIDs: [zoneID1, zoneID2])
    op.fetchRecordZonesCompletionBlock = { (dict, err) in
        if let err = err as? CKError, let _err = err.partialErrorsByItemID {                    
            print(_err) 
            /* prints 
            [AnyHashable(<CKRecordZoneID: 0x60800003cba0; ownerName=__defaultOwner__, zoneName=TestZone>): <CKError 0x60400005a760: "Zone Not Found" (26/2036); server message = "Zone 'TestZone' does not exist"; uuid = ...-2DF4E13F81E2; container ID = "iCloud.com.someContainer">]
            */

            // If I iterate through the dictionary
            _err.forEach({ (k, v) in
                print("key:", k) // prints: key: <CKRecordZoneID: 0x60800002d9e0; ownerName=__defaultOwner__, zoneName=TestZone>
                print("value:", v) // prints: value: <CKError 0x60400005a760: "Zone Not Found" (26/2036); server message = "Zone 'TestZone' does not exist"; uuid = ...-2DF4E13F81E2; container ID = "iCloud.com.someContainer

            })

            return
        }
        print("dict:", dict)
    }
    privateDB.add(op)
}

如何解析此错误?我需要访问zoneName吗?

1 个答案:

答案 0 :(得分:3)

_err中的密钥是CKRecordZoneID。完成后,请使用zoneName属性获取区域名称。

我将按照以下方式编写您的代码:

fileprivate func checkIfZonesWereCreated() {
    let privateDB = CKContainer.default().privateCloudDatabase
    let op = CKFetchRecordZonesOperation(recordZoneIDs: [zoneID1, zoneID2])
    op.fetchRecordZonesCompletionBlock = { (dict, err) in
        if let err = err as? CKError {
            switch err {
            case CKError.partialFailure:
                if let _err = err.partialErrorsByItemID {
                    for key in _err.keys {
                        if let zone = key as? CKRecordZoneID {
                            let name = zone.zoneName
                            print("Missing zone: \(name)")
                        }
                    }

                    return
                }
            default:
                break
            }
        }
        print("dict:", dict)
    }
    privateDB.add(op)
}