-1

我是 Swift 新手,想知道如何从异步任务中获取值。我有一个函数可以在返回时从 API 获取 Json 数据我想获取异步任务之外的特定字段的值...我的代码基本上在下面我有一个名为status的变量我想获取的值返回异步调用后的状态然后我想检查该值是否为 1 。在下面的代码中,返回的值是 1 但是似乎调用的异步是在if Status == 1 {}行之前执行的。如果值为 One 那么我想导航到不同的 ViewController 。任何建议都会很棒...我显然不能将代码放到异步代码中的不同 ViewController 中,因为它被调用了很多次。

 func GetData() {
   var status = 0
 // Code that simply contains URL and parameters
   URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
            if error != nil {
                print("Error")
            } else {
                do {

let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]

                    DispatchQueue.main.async {
                        if let Replies = parsedData["Result"] as? [AnyObject]  {


                            for Stream in Replies {

                                if let myvalue = Stream["status"] as? Int {
                                    status  = myvalue
                                }

                            }
                        }


                    }

                } catch let error as NSError {
                    print(error)
                }

            }

        }).resume()


       if status == 1 {
// This code is executed before the async so I don't get the value
        let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "Passed") as! Passed
        self.present(nextViewController, animated:false, completion:nil)
        }
}
4

1 回答 1

1

您可以像这样使用回调函数:

func GetData(callback: (Int) -> Void) {
    //Inside async task, Once you get the values you want to send in callback
    callback(status)
}

您将从调用函数的位置获得回调。

对于您的情况,Anbu 的回答也可以。

于 2018-05-04T04:37:16.983 回答