CloudKit: Fetch all records with a certain record type?

后端 未结 6 835
鱼传尺愫
鱼传尺愫 2021-02-05 19:50

I have currently got CloudKit set up in my app so that I am adding a new record using the help of the following code below,

CKRecordID *recordID         


        
6条回答
  •  臣服心动
    2021-02-05 20:10

    The followig function will return ALL records for requested record type:

    let database = CKContainer(identifier: "container_here").privateCloudDatabase
    typealias RecordsErrorHandler = ([CKRecord], Swift.Error?) -> Void
    
    func fetchRecords(forType type: String, completion: RecordsErrorHandler? = nil) {
    
        var records = [CKRecord]()
    
        let query = CKQuery(recordType: type, predicate: NSPredicate(value: true))
        let queryOperation = CKQueryOperation(query: query)
        queryOperation.zoneID = CloudAssistant.shared.zone.zoneID
    
        queryOperation.recordFetchedBlock = { record in
            records.append(record)
        }
    
        queryOperation.queryCompletionBlock = { cursor, error in
    
            self.fetchRecords(with: cursor, error: error, records: records) { records in
                completion?(records, nil)
            }
        }
    
        database.add(queryOperation)
    }
    
    private func fetchRecords(with cursor: CKQueryCursor?, error: Swift.Error?, records: [CKRecord], completion: RecordsHandler?) {
    
        var currentRecords = records
    
        if let cursor = cursor, error == nil {
    
            let queryOperation = CKQueryOperation(cursor: cursor)
    
            queryOperation.recordFetchedBlock = { record in
                currentRecords.append(record)
            }
    
            queryOperation.queryCompletionBlock = { cursor, error in
                self.fetchRecords(with: cursor, error: error, records: currentRecords, completion: completion)
            }
    
            database.add(queryOperation)
    
        } else {
            completion?(records)
        }
    }
    

提交回复
热议问题