Подтвердить что ты не робот

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

4b9b3361

Ответ 1

Вы должны вызвать свой UIAlertController в главном потоке, потому что вы имеете дело с пользовательским интерфейсом.

Swift 2.X

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)
    {

    }
}

Swift 4.2

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

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

    }
}

Ответ 2

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

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