UIKeyboardTaskQueue может быть вызван только из основного потока

У меня проблема при попытке создать функцию, которая автоматически создает запрос POST, отправляет их, получает ответ и обрабатывает их, а затем показывает UIAlertView, чтобы сообщить пользователю, какая это проблема.

Вот мой код:

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, но если ответ хороший, он выдает мне код ошибки, как указано выше.

2 ответа

Решение

Вы должны вызвать свой 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)
{

}

Для быстрой 3.x

DispatchQueue.main.async(execute: {
// work Needs to be done
 })
Другие вопросы по тегам