Swift cloudkit CKFetchRecordZoneChangesOptions无法返回删除记录

时间:2017-09-01 04:24:54

标签: swift icloud record cloudkit

我不知道为什么我无法在CKFetchRecordZoneChangesOptions上获取任何删除记录,我可以创建和修改记录,但delete无法删除记录。
在昨天,我可以正常删除更改记录。

这是我的代码

public func handleNotification(whichNotification : Int) {

    zoneID = UserDataCustomZone.zoneID

    if #available(iOS 10.0, *) {

        // Use the ChangeToken to fetch only whatever changes have occurred since the last
        // time we asked, since intermediate push notifications might have been dropped.
        var changeToken: CKServerChangeToken? = nil
        let changeTokenData = UserDefaults.standard.data(forKey: serverChangeTokenKey)

        if changeTokenData != nil {
            changeToken = NSKeyedUnarchiver.unarchiveObject(with: changeTokenData!) as! CKServerChangeToken?
        }

        let options = CKFetchRecordZoneChangesOptions()
        options.previousServerChangeToken = changeToken
        let optionsMap = [zoneID!: options]
        let operation = CKFetchRecordZoneChangesOperation(recordZoneIDs: [zoneID!], optionsByRecordZoneID: optionsMap)
        operation.fetchAllChanges = true
        // only can receive created and modified change record
        operation.recordChangedBlock = { record in
           //show record
            print("check this out \(record)")

            }

    }

    operation.recordZoneChangeTokensUpdatedBlock = { zoneID, changeToken, data in

        print("print Token \(String(describing: changeToken))")

        guard let changeToken = changeToken else {
            return
        }

        let changeTokenData = NSKeyedArchiver.archivedData(withRootObject: changeToken)
        UserDefaults.standard.set(changeTokenData, forKey: self.serverChangeTokenKey)
    }

    operation.recordZoneFetchCompletionBlock = { zoneID, changeToken, data, more, error in
        guard error == nil else {
            return
        }
        guard let changeToken = changeToken else {
            return
        }

        let changeTokenData = NSKeyedArchiver.archivedData(withRootObject: changeToken)
        UserDefaults.standard.set(changeTokenData, forKey: self.serverChangeTokenKey)
    }

    operation.fetchRecordZoneChangesCompletionBlock = { error in
        guard error == nil else {
            return
        }
    }

    operation.qualityOfService = .utility

    let container = CKContainer.default()
    let db = container.privateCloudDatabase
    db.add(operation)

     } else {
        // Fallback on earlier versions
    }

}

1 个答案:

答案 0 :(得分:0)

我注意到你已经定义了一个recordZoneChangeTokensUpdatedBlock处理程序,它足以接收记录创建和更新。但是,CKFetchRecordZoneChangesOperation通过其recordWithIDWasDeletedBlock处理程序通知记录删除。声明是:

var recordWithIDWasDeletedBlock: ((CKRecordID, String) -> Void)? { get set }

所以,基本上你需要包括以下额外的行:

operation.recordWithIDWasDeletedBlock = { recordID, recordType in ... }

在原始代码中。

请参阅Apple developer documentation以供参考。

整个过程和参考代码可以在Fetching Changes指南的Maintaining a Local Cache of CloudKit Records章节中找到。