无法使用CloudKit从公共数据库中获取记录

时间:2018-08-14 05:34:59

标签: ios swift cloudkit

这是我用来获取公共记录的方法:

private func fetchPublicRecordZonesChanges(completion: ErrorHandler?) {
    let zone = CKRecordZone.default()
    let options = CKFetchRecordZoneChangesOptions()
    options.previousServerChangeToken = nil

    var records = [CKRecord]()
    var recordIDsToDelete = [CKRecordID]()
    let operation = CKFetchRecordZoneChangesOperation(recordZoneIDs: [zone.zoneID], optionsByRecordZoneID: [zone.zoneID: options])
    operation.database = CloudAssistant.shared.publicDatabase
    operation.recordChangedBlock = { record in
        records.append(record)
    }

    operation.recordWithIDWasDeletedBlock = { recordID, string in
        recordIDsToDelete.append(recordID)
    }

    operation.recordZoneChangeTokensUpdatedBlock = { _, token, _ in
        if let token = token {
            Token.temporaryPublicZoneServerChangeToken = token
        }
    }

    operation.recordZoneFetchCompletionBlock = { [weak self] _, token, _, _, error in
        if let error = error, error.isTokenExpiredError {
            UserDefaults.remove(forKey: PublicZoneServerChangeTokenKey)
            self?.fetchPublicRecordZonesChanges(completion: completion)
            return
        }
        if let token = token {
            Token.temporaryPublicZoneServerChangeToken = token
        }
    }

    operation.fetchRecordZoneChangesCompletionBlock = { [weak self] error in
        self?.save(records: records, recordIDsToDelete: recordIDsToDelete) { error in
            completion?(error)
        }
    }
    operationQueue.addOperation(operation)
}

尽管调用了该方法,但是什么也不会获取,此外,甚至不会调用recordChangedBlock闭包。为什么?

我很确定我那里有记录:

enter image description here

和环境也很好,因为可以正确获取私有开发记录(当然使用不同的方法)。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

要通知您的公共数据库更改,请为您关心的记录类型创建一个CKQuerySubscription。这是一个示例:

let subscription = CKQuerySubscription(
  recordType: "Question", 
  predicate: NSPredicate(value: true), 
  subscriptionID: "subscriptionQuestion", 
  options: [
    .firesOnRecordCreation, 
    .firesOnRecordUpdate, 
    .firesOnRecordDeletion
  ])

let info = CKNotificationInfo()
info.shouldSendContentAvailable = true
subscription.notificationInfo = info

let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)

operation.modifySubscriptionsCompletionBlock = { saved, deleted, error in
  if let error = error{
    print("Add subscription error: \(error)")
  }else{
    print("Successfully added Question subscription.")
  }
}

//:::
let container = CKContainer(identifier: "...")
container.publicCloudDatabase.add(operation)