等待swift

时间:2016-01-18 18:11:28

标签: ios swift asynchronous

我想从Parse中检索用户分数并将其分配给变量。此函数在查询完成之前返回0。我在Retrieve object from parse.com and wait with return until data is retrieved找到了类似的答案。但是,我希望函数有一个返回值,并且在调用此函数时我应该使用什么参数作为completionhandler。任何帮助将不胜感激,谢谢!

这是我的代码

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
    }

1 个答案:

答案 0 :(得分:3)

设置此功能的方式不起作用,因为查询方法是异步的。这可以通过两种方式解决:

1)使用PFQuery同步类别: http://parse.com/docs/ios/api/Categories/PFQuery(Synchronous).html

这种方法的唯一缺点是该方法将变为阻塞,因此请务必从后台线程调用它。

2)重构函数以使用完成块而不是返回值.i.e:

    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);

            }
        }