2017-04-19 59 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