我的viewController中有一个findObjectsInBackgroundWithBlock方法。现在我想执行代码,但直到这个后台方法完成。我怎么能这样做?
我正在使用快速编程语言。
答案 0 :(得分:0)
parse.com上的文档和指南中已经详细介绍了这一点。但也许你有一个更具体的问题/场景?
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
编辑:PFUser的特定版本到用户名数组
var usernames: [String]?
func loadUsernames () {
if let query = PFUser.query() {
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil { // No error - should be good to go
self.userNames = (objects as! [PFUser]).map({$0.username!})
// Call/run any code you like here - remember 'self' keyword
// It will not run until userNames is populated
self.callSomeMethod()
} else { // Error - do something clever
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadUsernames()
}
答案 1 :(得分:0)
以下是一些可以帮助您的示例代码。目前尚不清楚如何限制代码(PRE-BACKGROUND CODE)仅在后台处理完成时运行。您可能希望在通知响应函数中插入一些代码,以确认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)
}
}