如何组合来自多个CloudKit表的数据?

时间:2016-12-20 19:04:07

标签: ios swift model cloudkit

我正在寻找一种方法将数据从多个CloudKit表加载到一个对象中。 现在我从一个CloudKit表(recordType)加载数据,但是如何在下面的函数中组合这些数据呢?我需要添加连接到Clients表的Activities表。因此,一个客户可以有多个活动。

我的客户端型号:

class Client: NSObject {
  var recordID: CKRecordID!
  var name: String?
  var activities: [Activity]?
  var image: UIImage?
  var email: String?
  var phone: String?
  var rate: Int?
}

我的活动对象:

class Activity: NSData {
  var name: String?
  var date: Date?
}

仅加载客户端的功能:

private func loadClients() {
    let pred = NSPredicate(value: true)
    let sort = NSSortDescriptor(key: "Name", ascending: true)
    let query = CKQuery(recordType: "Clients", predicate: pred)
    query.sortDescriptors = [sort]

    let operation = CKQueryOperation(query: query)

    var newClients = [Client]()

    operation.recordFetchedBlock = { record in
      let client = Client()
      client.recordID = record.recordID
      client.name = record["Name"] as? String
      client.email = record["Email"] as? String
      client.phone = record["Phone"] as? String
      client.rate = record["Rate"] as? Int

      newClients.append(client)
    }

    operation.queryCompletionBlock = { [unowned self] (cursor, error) in
      DispatchQueue.main.async {
        if error == nil {
          ViewController.isDirty = false
          self.clients = newClients

          if self.clients.count == 0 {
            self.messageLabel.text = "No values in the database"
          } else {
            self.tableView.reloadData()
          }

          self.updateView()
        } else {
          self.messageLabel.text = "Error loading data"
          print("ERROR: \(error!.localizedDescription)")
          self.updateView()
        }
      }
    }

    CKContainer.default().privateCloudDatabase.add(operation)
 }

1 个答案:

答案 0 :(得分:0)

据我了解,您希望使用一个请求加载Client Activity数组。

我认为使用CloudKit是不可能的。 但您可以在收到Activities记录后加载Client

    if let activitiesIDs = clientRecord["activities"] as? [CKRecordID] {
        let operation = CKFetchRecordsOperation(recordIDs: activitiesIDs)
        operation.fetchRecordsCompletionBlock = { (records, error) in

        }

        let database = CKContainer.default().publicCloudDatabase
        database.add(operation)
    }