2016-09-18 33 views
11

我有一个问题,试图做一个函数,自动创建POST请求,发送它们,获取响应,并处理它们,然后显示UIAlertView告诉用户它是哪个问题。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

您应该在主线程上调用您的UIAlertController,因为您正在处理ui。

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

为SWIFT 3.x的

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