[英]Wait for async function return value in swift
I want to retrieve the user score from Parse and assign it to a variable. 我想从Parse中检索用户分数并将其分配给变量。 This function returns 0 before the query finishes.
此函数在查询完成之前返回0。 I have found a similar answer at Retrieve object from parse.com and wait with return until data is retrieved .
我在parse.com的Retrieve对象中找到了类似的答案, 并等待返回直到检索到数据 。 However, I expect the function have a return value and what argument should I use for the completionhandler when calling this function.
但是,我希望函数有一个返回值,并且在调用此函数时我应该使用什么参数作为completionhandler。 Any help would be appreciated, thanks!
任何帮助将不胜感激,谢谢!
Here is my code 这是我的代码
func loadCurrentUserData() -> Int {
let query = PFQuery(className: "userScore")
let userId = PFUser.currentUser()!
var currentUserScore: Int = 0
query.whereKey("user", equalTo: userId)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let scoreReceived = objects![0]["score"] as! Int
currentUserScore = scoreReceived
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.userScore.text = "\(scoreReceived)"
})
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
return currentUserScore
}
The way you have set this function will not work as the query method is asynchronous. 设置此函数的方式不起作用,因为查询方法是异步的。 This can be fixed in two ways:
这可以通过两种方式解决:
1) Use the PFQuery synchronous category: http://parse.com/docs/ios/api/Categories/PFQuery(Synchronous).html 1)使用PFQuery同步类别: http ://parse.com/docs/ios/api/Categories/PFQuery (Synchronous)。
The only disadvantage to this approach is that the method will become blocking so make sure to call it from a background thread. 这种方法的唯一缺点是该方法将变为阻塞,因此请确保从后台线程调用它。
2) Restructure the function to use a completion block instead of a return value..ie: 2)重构函数以使用完成块而不是返回值.ie:
func loadCurrentUserData(completion: (score: Int!, error: NSError?) ->()) {
let query = PFQuery(className: "userScore")
let userId = PFUser.currentUser()!
var currentUserScore: Int = 0
query.whereKey("user", equalTo: userId)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let scoreReceived = objects![0]["score"] as! Int
currentUserScore = scoreReceived
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.userScore.text = "\(scoreReceived)"
})
completion(score: currentUserScore, error: nil);
} else {
print("Error: \(error!) \(error!.userInfo)")
}
completion(score: currentUserScore, error: error);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.