我怎么能等到从parse.com检索数据?
这是我的函数,它返回一个空字符串,因为来自parse.com的响应太慢了。如果我在成功区域内放置一个断点,它将在需要数据后“断开”。我想有一种方法可以让数据同步,所以它会等待吗?
func getObjectId(localPersonId:NSString) -> NSString{
var currentObjectId:NSString = ""
var query = PFQuery(className:"myClass")
query.whereKey("personId", equalTo:localPersonId)
query.whereKey("groupId", equalTo:self.currentGroupId)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// should not use a for loop since this should
// only return one row
for object in objects {
currentObjectId = object["objectId"] as NSString
}
} else {
// Log details of the failure
NSLog("Error: %@ %@", error, error.userInfo!)
}
}
return currentObjectId
}
在这种情况下,getObjectId函数将返回一个空字符串。任何人吗?
答案 0 :(得分:2)
我意识到这已经有3个月了,但是虽然Parse文档非常好/有用,但在回答IOS Parse相关问题时并没有很多。
这应该有效。它使用完成处理程序,这是处理此问题的简单方法。
(有关异步上下文中完成处理程序的更多信息:https://thatthinginswift.com/completion-handlers/)
func getObjectId(localPersonId:NSString, completionHandler: (currentObjectId: [String]) -> ()){
var currentObjectId:NSString = ""
var query = PFQuery(className:"myClass")
query.whereKey("personId", equalTo:localPersonId)
//query.whereKey("groupId", equalTo:self.currentGroupId)
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
if error == nil {
// should not use a for loop since this should
// only return one row
for object in objects {
completionHandler(currentObjectId: currentObjectId)
}
} else {
// Log details of the failure
NSLog("Error: %@ %@", error!, error!.userInfo!)
}
}
}