2016-11-09 38 views
1

我想用傳送URLSession.shared.dataTask呼叫performSegue後URLSession.shared.dataTask

視圖控制器POST請求後performe一個Segue公司:

@IBAction func Connection(_ sender: AnyObject) { 
    let loginFunc = Login() 
    loginFunc.login(username: username.text!, password: password.text!) { jsonString in 
     let response = jsonString 
     print(response) 
     if response.range(of: "failure") == nil { 
      self.performSegue(withIdentifier: "home", sender: nil) 
     } 
    } 
} 

登錄:

class Login { 
// the completion closure signature is (String) ->() 
func login(username: String, password: String, completion: @escaping (String) ->()) { 
    var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/login_check")!) 
    request.httpMethod = "POST" 
    let postString = "_username=" + username + "&_password=" + password 
    request.httpBody = postString.data(using: .utf8) 
    var responseString = "" 
    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     guard let data = data, error == nil else {             // check for fundamental networking error 
      print("error=\(error)") 
      return 
     } 

     if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
      print("response = \(response)") 
     } 

      responseString = String(data: data, encoding: .utf8)! 
      completion(responseString) 
     } 
     task.resume() 
    } 
} 

它有時會與以下錯誤錯誤

終止應用程序由於未捕獲的異常 'NSInternalInconsistencyException',原因: ' - [UIKeyboardTaskQueue waitUntilAllTask​​sAreFinished]可以僅從主線程稱爲'。

有沒有更好的方法來做到這一點?

+1

嘗試派遣你的'performSegue '回到主隊列。 –

回答

2

嘗試這種方式:

if response.range(of: "failure") == nil { 
      NSOperationQueue.mainQueue().addOperationWithBlock { 
       self.performSegue(withIdentifier: "home", sender: nil) 
      } 
     } 

swift3:

if response.range(of: "failure") == nil { 
      OperationQueue.main.addOperation { 
       self.performSegue(withIdentifier: "home", sender: nil) 
      } 
} 
+0

它工作得非常好!如果我理解得好OperationQueue正在等待之前完成Sergue的請求? – ZeenaZeek

+0

是的!操作將保留在該隊列中,直到它被明確取消或完成其任務 –

1

由於錯誤說你需要調用在主線程中執行賽格瑞這樣

DispatchQueue.main.async { 
    self.performSegue(withIdentifier: "home", sender: nil) 
}