将完成块添加到CloudKit函数

时间:2016-02-14 11:57:02

标签: swift cloudkit completion-block

我的ViewController想要根据CloudKit查询显示一些数据。

我的CloudKit代码都在一个单独的类中。该类有一个名为loadExpenses()的函数,它从CK中获取一些Expenses实体。

我希望能够从VC调用loadExpenses(),因此我需要该函数提供的完成块来从VC更新UI。

这就是loadExpenses()的样子:

func loadExpenses() {
    let pred = NSPredicate(value: true)
    let sort = NSSortDescriptor(key: "creationDate", ascending: true)
    let query = CKQuery(recordType: "Expense", predicate: pred)
    query.sortDescriptors = [sort]

    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["person", "action", "amount", "timestamp"]
    operation.resultsLimit = 50

    var newExpenses = [Expense]()

    operation.recordFetchedBlock = { (record) in
        let recordID = record.recordID
        let person = record["person"] as! String
        let action = record["action"] as! String
        let amount = record["amount"] as! Double
        let timestamp = record["timestamp"] as! NSDate
        let expense = Expense(person: person, action: action, amount: amount, timestamp: timestamp)
        newExpenses.append(expense)
    }

    // This is the part that needs to be changed
    operation.queryCompletionBlock = { [unowned self] (cursor, error) in
        dispatch_async(dispatch_get_main_queue()) {
            if error == nil {
                self.objects = newExpenses
                self.tableView.reloadData()
                self.refreshRealmDataFromCK()
            } else {
                let ac = UIAlertController(title: "Fetch failed", message: "There was a problem fetching the list of expenses; please try again: \(error!.localizedDescription)", preferredStyle: .Alert)
                ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
                self.presentViewController(ac, animated: true, completion: nil)
            }
        }
    }
    CKContainer.defaultContainer().privateCloudDatabase.addOperation(operation)
}

显然最后一部分不会执行,考虑到所有那些self.property属于VC(我保留它们只是为了表明我需要在VC中做什么)。

正如我所说,我希望能够从VC调用此函数并获取/使用完成块来更新这些属性。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要将块作为参数传递给loadExpenses()函数。所以它实际上应该被定义为loadExpenses(completionBlock:([whatever parameters you need in here])->Void)

然后,您可以在completionBlock块中调用传递的operation.queryCompletionBlock块(带有适当的参数)。

修改

所以当然没有经过测试,但你可以试一试:

func loadExpenses(completionBlock:([Expense])->Void) {
    let pred = NSPredicate(value: true)
    let sort = NSSortDescriptor(key: "creationDate", ascending: true)
    let query = CKQuery(recordType: "Expense", predicate: pred)
    query.sortDescriptors = [sort]

    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["person", "action", "amount", "timestamp"]
    operation.resultsLimit = 50

    var newExpenses = [Expense]()

    operation.recordFetchedBlock = { (record) in
        let recordID = record.recordID
        let person = record["person"] as! String
        let action = record["action"] as! String
        let amount = record["amount"] as! Double
        let timestamp = record["timestamp"] as! NSDate
        let expense = Expense(person: person, action: action, amount: amount, timestamp: timestamp)
        newExpenses.append(expense)
    }

    // This is the part that needs to be changed
    operation.queryCompletionBlock = { [unowned self] (cursor, error) in
        completionBlock(newExpenses)
    }
    CKContainer.defaultContainer().privateCloudDatabase.addOperation(operation)
}

然后像这样称呼它:

loadExpenses({ (newExpenses:[Expense]) -> Void in {
    dispatch_async(dispatch_get_main_queue()) {
        if error == nil {
            self.objects = newExpenses
            self.tableView.reloadData()
            self.refreshRealmDataFromCK()
        } else {
            let ac = UIAlertController(title: "Fetch failed", message: "There was a problem fetching the list of expenses; please try again: \(error!.localizedDescription)", preferredStyle: .Alert)
            ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(ac, animated: true, completion: nil)
        }
    }
}