查看来自URLSession的响应

时间:2017-04-19 17:48:06

标签: swift3 nsurlsession

我有一个端点,它接收一个电话号码并向该号码发送一个代码,但也会将相同的消息返回给调用它的会话的数据部分。 所有这些都有效,但我遇到的问题是,在会话发出呼叫之后,我将转到下一个屏幕并将该代码传递到下一个控制器。但我认为api的响应速度太慢,所以到时候segue(和segue的准备)已经发生了,代码还没有被返回。我该如何解决这个问题?

let scriptURL = "https://---------------/api/verify/sms?"
    let urlWithParams = scriptURL + "number=\(phone.text!)"
    let myUrl = NSURL(string: urlWithParams)
    let request = NSMutableURLRequest(url: myUrl! as URL)

    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in
        //print(error?.localizedDescription)

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
            self.currentCode = json["code"]!! as! String //-> This is the code the is returned from the api call 

        }catch{
            print("error with serializing JSON: \(error)")
        }
    }
    task.resume()

    self.performSegue(withIdentifier: "toVerifyCode", sender: (Any?).self)
}

// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if segue.identifier == "toVerifyCode"{
        let newController = segue.destination as! verifyCodeController
        newController.code = self.currentCode
    }
}

1 个答案:

答案 0 :(得分:0)

问题是你没有把self.performSegue(withIdentifier: "toVerifyCode", sender: (Any?).self)放在闭包中。

所以,你必须这样放置它:

let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in
        //print(error?.localizedDescription)

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject

            //on main thread
            DispatchQueue.main.async {
                self.currentCode = json["code"]!! as! String //-> This is the code the is returned from the api call
                self.performSegue(withIdentifier: "toVerifyCode", sender: (Any?).self)
            }

        }catch{
            print("error with serializing JSON: \(error)")
        }
    }
    task.resume()

另外,请注意你的闭包是异步执行的,因此我使用GCD将调用包装在主线程上执行。

相关问题