快速等待异步函数返回值 [英] Wait for async function return value in swift

查看:120
本文介绍了快速等待异步函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Parse中检索用户得分并将其分配给变量.查询结束前,此函数返回0.我在从parse.com检索对象,然后等待返回,直到检索到数据为止.但是,我希望该函数具有返回值,并且在调用此函数时应为completionhandler使用什么参数.任何帮助将不胜感激,谢谢!

I want to retrieve the user score from Parse and assign it to a variable. This function returns 0 before the query finishes. I have found a similar answer at Retrieve object from parse.com and wait with return until data is retrieved. However, I expect the function have a return value and what argument should I use for the completionhandler when calling this function. Any help would be appreciated, thanks!

这是我的代码

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)使用PFQuery同步类别: http://parse.com/docs/ios/api/Categories/PFQuery(Synchronous).html

1) Use the PFQuery synchronous category: http://parse.com/docs/ios/api/Categories/PFQuery(Synchronous).html

此方法的唯一缺点是该方法将被阻塞,因此请确保从后台线程调用它.

The only disadvantage to this approach is that the method will become blocking so make sure to call it from a background thread.

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

2) Restructure the function to use a completion block instead of a return value..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);

            }
        }

这篇关于快速等待异步函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆