DispatchQueue : Cannot be called with asCopy = NO on non-main thread

Amit picture Amit · Oct 15, 2018 · Viewed 22.2k times · Source

I am presenting the UIAlertController on the main thread as :

class HelperMethodClass: NSObject {

    class func showAlertMessage(message:String, viewController: UIViewController) {
        let alertMessage = UIAlertController(title: "", message: message, preferredStyle: .alert)

        let cancelAction = UIAlertAction(title: "Ok", style: .cancel)

        alertMessage.addAction(cancelAction)

        DispatchQueue.main.async {
            viewController.present(alertMessage, animated: true, completion: nil)
        }
    }
}

And I am calling the method from any UIViewController as:

HelperMethodClass.showAlertMessage(message: "Any Message", viewController: self)

I am getting the output properly.

But in console I am getting below message:

[Assert] Cannot be called with asCopy = NO on non-main thread.

Is there something I have done wrong here or I can ignore this message ?

Edit

Thanks to @NicolasMiari :

Adding below code is not showing any message:

DispatchQueue.main.async {
    HelperMethodClass.showAlertMessage(message: "Any Message", viewController: self)
}

What can be the reason that previously it was showing the message in console?

Answer

Ilya Kharabet picture Ilya Kharabet · Oct 15, 2018

You should call all code from showAlertMessage on main queue:

class func showAlertMessage(message:String, viewController: UIViewController) {
    DispatchQueue.main.async {
        let alertMessage = UIAlertController(title: "", message: message, preferredStyle: .alert)

        let cancelAction = UIAlertAction(title: "Ok", style: .cancel)

        alertMessage.addAction(cancelAction)

        viewController.present(alertMessage, animated: true, completion: nil)
    }
}