CloudKit CKFetchRecordsOperation块

时间:2016-11-04 15:51:03

标签: swift cloudkit

我正在使用CKFetchRecordsOperation获取一些云记录。 operation.perRecordCompletionBlock闭包有一个查询来获取一些子记录,但我注意到在operation.completionBlock完成工作之前调用perRecordCompletionBlock闭包。那么,我应该在哪里调用我的完成闭包,通知该操作完成所有操作?

func getResidents(completion: @escaping (_ residents: [Resident]?, _ error: Error?) -> Void) {

    var residents = [Resident]()
    let recordNames = ["a56e39ad-9078-43b2-b699-5b9faa233f0d",
                       "e842daaa-3ff2-434b-9d50-3f14eb7e46d5",
                       "5cf075ad-d78a-4cea-872e-6b062781f14c",
                       "8e9fdbbb-cf06-486f-9fae-8be13abe2357",
                       "78b0cc19-9e33-4755-b199-7098fa319368",
                       "2d9bee21-d268-46cc-84e1-f7784495aac2",
                       "ae1da81b-bc1d-4e83-b145-c06882dc2203",
                       "3e13ed1e-e007-4ece-9a6c-8c09d638d6b3",
                       "78c224ab-e836-48c9-8c1c-f10bd4907457"
                       ]

    func getRecordIDs(names: [String]) -> [CKRecordID] {
        var IDs = [CKRecordID]()
        for name in names {
            IDs.append(CKRecordID(recordName: name))
        }
        return IDs
    }

    let operation = CKFetchRecordsOperation(recordIDs: getRecordIDs(names: recordNames))
    operation.perRecordCompletionBlock = { record, recordID, error in
        if error != nil {
            completion(nil, error)
        } else {
            if let record = record {
                // Query debts (resident children)
                let predicate = NSPredicate(format: "Resident = %@", record.recordID)
                let query = CKQuery(recordType: Constants.RecordType.Debt, predicate: predicate)
                self.publicCloudDB.perform(query, inZoneWith: nil) { records, error in
                    if error != nil {
                        // Retain the record IDs for failed fetches
                        completion(nil, error)
                    } else {
                        var debts = [Debt]()
                        if let debtRecords = records {
                            for item in debtRecords {
                                if let debt = Debt.parse(record: item) {
                                    debts.append(debt)
                                }
                            }
                        }
                        if var resident = Resident.parse(record: record) {
                            resident.debts = debts
                            residents.append(resident)
                            print(resident)
                        }
                    }
                }
            }
        }
    }

    operation.completionBlock = {
        completion(residents, nil)
    }

    operation.allowsCellularAccess = true
    operation.database = publicCloudDB
    operation.start()
}

0 个答案:

没有答案