2016-09-18 6 views
11

POSTリクエストを自動的に作成して送信し、応答を取得し、それらを処理し、ユーザーにどの問題があるかを示す関数を作成しようとしているときに問題があります。UIKeyboardTaskQueueはメインスレッドからのみ呼び出すことができます

let task = session.dataTaskWithRequest(request, completionHandler:{ (data, response, error) -> Void in 

    dispatch_async(dispatch_get_main_queue(),{ 
     var alert = UIAlertController(title: "Chargement", message: "Envoi des informations...", preferredStyle: UIAlertControllerStyle.Alert) 
     viewController.presentViewController(alert, animated: true, completion: nil) 


     answer = NSString(data: data!, encoding: NSUTF8StringEncoding)! 
     print(answer) 
    var complete = false 
    alert.dismissViewControllerAnimated(true, completion: {() -> Void in 
     complete = true 
    }) 

    while(!complete) 
    { 

    } 
    var textmsg: String 
    if(answer == "#400") 
    { 
     textmsg = "Il manque une information !" 
    } 
    else if(answer == "#50") 
    { 
     textmsg = "Le compte fourni ne correspond pas." 
    } 
    else if(answer == "#100") 
    { 
     textmsg = "Impossible d'identifier l'application." 
    } 
    else if(answer == "#1") 
    { 
     textmsg = "Transfert terminé avec succès !" 
    } 
    else { 
     textmsg = "Echec du transfert." 
    } 
    let alertComplete = UIAlertController(title: "Chargement", message: textmsg, preferredStyle: UIAlertControllerStyle.Alert) 
    alertComplete.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) 
    viewController.presentViewController(alertComplete, animated: true, completion: nil) 
    }) 
}) 

task.resume(); 

エラーコードは以下の通りです:ここで

は私のコードです

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.' 

私の要求は悪い応答(#400、#50、#100)を返した場合、コードが動作し、UIAlertViewが表示されますが、応答が良ければ、上記のエラーコードが表示されます。

答えて

17

あなたはuiを扱っているので、メインスレッドでUIAlertControllerを呼び出す必要があります。

dispatch_async(dispatch_get_main_queue(),{ 
      var alert = UIAlertController(title: "Chargement", message: "Envoi des informations...", preferredStyle: UIAlertControllerStyle.Alert) 
      viewController.presentViewController(alert, animated: true, completion: nil) 

      answer = NSString(data: data!, encoding: NSUTF8StringEncoding)! 
      print(answer) 
     var complete = false 
alert.dismissViewControllerAnimated(true, completion: {() -> Void in 
    complete = true 
}) 
while(!complete) 
{ 

} 
+0

しかし、UIは、私のサーバーのリターン#400、#50または#100で動作しますので、私はそれが成功の声明から来るだと思う:/ – Orionss

+0

あなたがしていますあなたが応答を受け取ったときに、別のスレッドのUI要素を扱いますが、あなたはメインスレッドだけでUIを扱うことになっています。 –

+0

私はこれを試しましたが(私は新しいコードをアップロードしました)、動作していないようです... – Orionss

12
迅速3.xの

DispatchQueue.main.async(execute: { 
// work Needs to be done 
})