我的 viewController 中有一个 findObjectsInBackgroundWithBlock 方法。现在我想执行代码,但直到这个后台方法完成为止。我怎样才能做到这一点?
我正在使用 swift 编程语言。
最佳答案
这里是一些可以帮助您的示例代码。目前尚不清楚如何限制代码(后台前代码)仅在后台处理完成时运行。您可能需要在通知响应函数中插入一些代码,以确认 PRE-BACKGROUND CODE 已完成或终止它。
// ParseTestViewController.swift
import UIKit
import Foundation
import Parse
class ParseTestViewController: UIViewController {
var userData = [String]()
func codeToExecuteBeforeStringsAreAppended() {
}
func codeToExecuteAfterStringsAreAppended() {
// can use the array 'userData'
}
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "notificationResponse:",
name: "recordsLoaded",
object: nil
)
self.getUserdataForUsername("MyName")
/* ==========================
Insert code tto be executed immediately after making the call that must not use the data returned by Parse. The function returns right away and the background may not have completed.
*/
codeToExecuteBeforeStringsAreAppended()
}
func getUserdataForUsername (queryUserName: String) {
var query = PFQuery(className:"UserData")
query.whereKey("username", equalTo: queryUserName)
let notification = NSNotification(name: "userDataRetrieved", object: self)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
if let username = object["username"] as? String {
self.userData.append (username)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
NSNotificationCenter.defaultCenter().postNotification(notification)
}
}
func notificationResponse (notification: NSNotification) {
// this is executed after the background processing is done
// Insert the code that uses the data retrieved from Parse
codeToExecuteAfterStringsAreAppended()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
关于swift - 在后台进程后运行代码 - parse.com,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31248787/