解析 CloudKit 错误 (CKError)

Parsing CloudKit Error (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 ?

_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)
}