CloudKit:获取具有特定记录类型的所有记录?

时间:2015-02-09 04:32:57

标签: ios icloud cloudkit ckrecord

我目前在我的应用中设置了 CloudKit ,以便我使用以下代码的帮助添加新记录,

CKRecordID *recordID = [[CKRecordID alloc] initWithRecordName:@"stringArray"];
CKRecord *record = [[CKRecord alloc] initWithRecordType:@"Strings" recordID:recordID];
[record setObject:[NSArray arrayWithObjects:@"one", @"two", @"three", @"four", nil] forKey:@"stringArray"];
[_privateDatabase saveRecord:record completionHandler:nil];

但是,现在我希望能够获取具有相同记录类型的所有记录“Strings”,并将这些记录返回到NSArray中。我该怎么做呢?目前,我所知道的是如何使用recordID单独获取每条记录,这是一个麻烦,必须有一个更简单的方法。

[_privateDatabase fetchRecordWithID:recordID completionHandler:^(CKRecord *record, NSError *error) {
   if (error) {
      // Error handling for failed fetch from private database
   }
   else {
      NSLog(@"ICLOUD TEST: %@", [record objectForKey:@"stringArray"]);            
  }
}];

6 个答案:

答案 0 :(得分:8)

Aaaand,我知道了。使用下面的代码,我能够创建一个在数据库上运行的查询,然后在完成块中返回一个NSArray,我循环访问,并在NSLog中返回已保存密钥的值。

NSPredicate *predicate = [NSPredicate predicateWithValue:YES];
CKQuery *query = [[CKQuery alloc] initWithRecordType:@"Strings" predicate:predicate];

[_privateDatabase performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error) {
    for (CKRecord *record in results) {
        NSLog(@"Contents: %@", [record objectForKey:@"stringArray"]);
    }
}];

答案 1 :(得分:6)

Swift 4 的解决方案, 显示如何获取“YourTable”类型的所有记录,同时打印System FieldCustom Field

let query = CKQuery(recordType: "YourTable", predicate: NSPredicate(value: true))
CKContainer.default().publicCloudDatabase.perform(query, inZoneWith: nil) { (records, error) in
  records?.forEach({ (record) in

    // System Field from property
    let recordName_fromProperty = record.recordID.recordName
    print("System Field, recordName: \(recordName_fromProperty)")

    // Custom Field from key path (eg: deeplink)
    let deeplink = record.value(forKey: "deeplink")
    print("Custom Field, deeplink: \(deeplink ?? "")")
  })
}

答案 2 :(得分:2)

以下是Swift 3.0中的答案。

func myQuery()  {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "tableName", predicate: predicate)

    publicDatabase.perform(query, inZoneWith: nil) { (record, error) in

        for record: CKRecord in record! {
            //...

            // if you want to access a certain 'field'.
            let name = record.value(forKeyPath: "Name") as! String                
        }
    }
}

答案 3 :(得分:0)

followig函数将返回所请求记录类型的所有记录:

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

答案 4 :(得分:0)

在尝试获取所有记录并了解Cloudkit存储的结构和详细信息时,我发现在调试过程中提供以下功能很有用。这使用信号量来保留用于打印的数据结构。可能有一种更优雅的方法可以做到这一点,但这有效!

//
// Print a list of records in all zones in all databases
//
func printRecordsInContainers() {

    let myContainer = CKContainer.default()
    // Edit the following dictionary to include any known containers and possible record types
    let containerRecordTypes: [CKContainer: [String]] = [ myContainer: ["MyRecordType", "OldRecordType", "MyUser", "PrivateInfo"] ]
    let containers = Array(containerRecordTypes.keys)

    for containerz in containers {
        let databases: [CKDatabase] = [containerz.publicCloudDatabase, containerz.privateCloudDatabase, containerz.sharedCloudDatabase]

        for database in databases {
            var dbType = "<None>"
            if database.databaseScope.rawValue == 1 { dbType = "Public" }
            if database.databaseScope.rawValue == 2 { dbType = "Private" }
            if database.databaseScope.rawValue == 3 { dbType = "Shared" }

            //print("\(database.debugDescription)")
            print("\n\n\n ---------------------------------------------------------------------------------------------------")
            print(" ----- Container: \(containerz.containerIdentifier ?? "??") ----- Database: \(dbType)")
            let semaphore1 = DispatchSemaphore(value: 0)     // Initiate semaphore1 to wait for closure to return

            database.fetchAllRecordZones { zones, error in
                if let error = error {
                    print(" Error Fetching Zones: \(error.localizedDescription)")
                }
                else if let zones = zones {
                    print("~~~~ \(zones.count) : \(zones)")
                    for zone in zones {
                        print("----- Zone ID: \(zone.zoneID)\n")
                        for recordType in containerRecordTypes[container] ?? [] {
                            print("[  Record Type: \(recordType.description)  ]")
                            let query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true))

                            let semaphore = DispatchSemaphore(value: 0)     // Initiate semaphore to wait for closure to return
                            database.perform(query, inZoneWith: zone.zoneID) { records, error in
                                if let error = error {
                                    print(" Error in Record Query: \(error.localizedDescription)")
                                }
                                else if let records = records {
                                    printRecordDescriptions(records)
                                }
                                semaphore.signal()      // Send semaphore signal to indicate closure is complete
                            }
                            semaphore.wait()            // Wait for semaphore to indicate that closure is complete
                        }
                    }
                }
                else {
                    print(" Error in fetchAllRecordZones")
                }
                semaphore1.signal()      // Send semaphore1 signal to indicate closure is complete
            }
            semaphore1.wait()            // Wait for semaphore1 to indicate that closure is complete
        }
    }
}
class func printRecordDescriptions(_ records: [CKRecord]) {
    print("Records and Contents List:")
    for record in records {
        print(" Record: \(record.recordID)")
        for key in record.allKeys() {
            print("    Key - \(key)")
        }
    }
    print("Record List End\n")
}

答案 5 :(得分:0)

快速5

查看了SO上的大量帖子和解决方案后,我设法提供了一个适合我的需求的解决方案,对于只想从iCloud中获取所有给定类型的所有记录的人来说,它应该足够简单。

解决方案

该解决方案使用CKDatabase的扩展引入一种处理cursor: CKQueryOperation.Cursor的{​​{1}}的方法,以继续向iCloud请求更多记录。在这种方法中,我将分派到后台队列,以便可以将其阻止,并在收到错误或最后一批记录时等待操作完全完成。信号量解锁队列后,它将继续调用结果的主完成块。另外,我在完成处理程序中利用了Swift的CKQueryOperation类型。

Result

用法

对于熟悉Swift的闭包语法和extension CKDatabase { func fetchAll( recordType: String, resultsLimit: Int = 100, timeout: TimeInterval = 60, completion: @escaping (Result<[CKRecord], Error>) -> Void ) { DispatchQueue.global().async { [unowned self] in let query = CKQuery( recordType: recordType, predicate: NSPredicate(value: true) ) let semaphore = DispatchSemaphore(value: 0) var records = [CKRecord]() var error: Error? var operation = CKQueryOperation(query: query) operation.resultsLimit = resultsLimit operation.recordFetchedBlock = { records.append($0) } operation.queryCompletionBlock = { (cursor, err) in guard err == nil, let cursor = cursor else { error = err semaphore.signal() return } let newOperation = CKQueryOperation(cursor: cursor) newOperation.resultsLimit = operation.resultsLimit newOperation.recordFetchedBlock = operation.recordFetchedBlock newOperation.queryCompletionBlock = operation.queryCompletionBlock operation = newOperation self?.add(newOperation) } self?.add(operation) _ = semaphore.wait(timeout: .now() + 60) if let error = error { completion(.failure(error)) } else { completion(.success(records)) } } } } 类型的人来说,使用该方法非常简单。

Result