如何从CloudKit查询和获取数据?

时间:2015-12-05 01:33:50

标签: ios swift cloudkit

我是Swift的新手,本周刚开始学习关于CloudKit的iOS应用程序项目。

数据库正在运行,我可以添加记录并在数据库中查找记录。

我遇到了向CloudKit发送查询并访问与查询相关的数据的问题。

CloudKit数据具有唯一标识符,因此搜索其中一个标识符(因此查询应仅返回一条记录)。然后,我试图从该记录中获取三条信息 - " UPC"," foodName"," Ingredients" (所有字符串)

以下是执行查询并尝试获取数据的代码部分。

let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase

let predicate = NSPredicate(format: "UPC = %@", subStr)

let query = CKQuery(recordType: "Food", predicate: predicate)

publicDatabase.performQuery(query, inZoneWithID: nil,
                    completionHandler: ({results, error in

       if (error != nil) {
           dispatch_async(dispatch_get_main_queue()) {
                     print("CloudKit Error")
                            }
                        } else {
        if results!.count > 0 {

            var record = results as! CKRecord

            dispatch_async(dispatch_get_main_queue()) {

            print("UPC Found")
            let cloudUPC = record.objectForKey("UPC") as! CKAsset
            print("UPC from CloudKit \(cloudUPC)")

                }
            } else {
               dispatch_async(dispatch_get_main_queue()) {
                                    print("UPC Not Found")
                                }
                            }
                        }
                    }))

此时发生崩溃

 var record = results as! CKRecord

并返回" EXC_Breakpoint(代码= 1,子代码 - 0x10047b7c)

有关如何解决此问题的任何建议?

由于

2 个答案:

答案 0 :(得分:1)

感谢rmaddy的建议。

这是我修复代码的方法

let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase

let predicate = NSPredicate(format: "UPC = %@", subStr)

let query = CKQuery(recordType: "Food", predicate: predicate)

publicDatabase.performQuery(query, inZoneWithID: nil,
                completionHandler: ({results, error in

                    if (error != nil) {
                        dispatch_async(dispatch_get_main_queue()) {
                            print("Cloud Error")
                        }
                    } else {
                        if results!.count > 0 {


          dispatch_async(dispatch_get_main_queue()) {


         for entry in results! {
         let cloudUPC = entry["UPC"] as? String
         print("UPC from CloudKit \(cloudUPC)")

         let cloudFoodName = entry["foodName"] as? String
         print("Name from CloudKit \(cloudFoodName)")

         let cloudIngredients = entry["Ingredients"] as? String
         print("Ingredients from CloudKit \(cloudIngredients)")

          }
        } else {
           dispatch_async(dispatch_get_main_queue()) {
                                print("UPC Not Found")
                            }
                        }
                    }
                }))

答案 1 :(得分:0)

你需要先写入记录中的项目循环然后打印每个UPC 那样:

for item in record {
print(item["UPC"]
print(item["foodName"]
}