2016-11-09 4 views
1

私は コールperformSegue後URLSession.shared.dataTask

のViewControllerをURLSession.shared.dataTask

を使用してPOSTリクエストを送信した後にセグエをperformeたい:

@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

のようにメインスレッドでセグエを行う呼び出す必要が言うように'メインキューに戻ります。 –

答えて

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

エラーは、あなたの `performSegueを派遣してみこの

DispatchQueue.main.async { 
    self.performSegue(withIdentifier: "home", sender: nil) 
} 
関連する問題