2017-04-19 62 views
0

我有一个端点,它接收一个电话号码并向该号码发送一个代码,但也会将相同的消息返回给调用它的会话的数据部分。 所有这些工作,但我遇到的问题是,在会话进行调用后,我继续到下一个屏幕,我将该代码传递到下一个控制器。但我认为api的响应速度太慢了,所以到时候segue(并准备继续)发生了,代码还没有返回。我怎样才能解决这个问题?查看来自URLSession的响应

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 
    } 
} 
+0

把'performSegue(withIdentifier' ** **添加到**完成块中 – vadian

+0

所以我试过了,同样的事情似乎还在发生? –

+0

代码应该工作如果行被放在'self.currentCode = json [...'line,当然会在'resume()'之后被移除。Btw:只传递'nil'作为发送者,而在使用'GET'时不需要'URLRequest'。 – vadian

回答

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在主线程上执行调用。

+0

谢谢!有效 –

+0

@CesaSalaam你非常欢迎。 – Shmidt