在 Swift 3.0 中从异步线程调用 UIAlertController

Calling a UIAlertController from Asynchronous Thread in Swift 3.0

我有一个 IBAction 调用一个有时会显示来自异步线程的错误警报的函数。它在模拟器中 "works",但我得到了这个错误:

CoreAnimation: warning, deleted thread with uncommitted CATransaction; set CA_DEBUG_TRANSACTIONS=1 in environment to log backtraces.

看到那个错误后,我意识到我正在尝试从主线程更新 UI,我需要修复它。

这是我正在调用的异步函数:

let queue = DispatchQueue(label: "com.adrianbindc.myApp.myFunction")

queue.async {
    self.createArray()

    switch self.arrayIsEmpty() {
    case true:
        // TODO: update on the main thread
        self.displayAlert(alertTitle: "Error Title", alertMessage: "Error Message")
    case false:

        // Do Stuff Off the Main Queue
        DispatchQueue.main.async{
            switch someArray.count {
            case 0:
                // TODO: update on the main thread
                self.displayAlert(alertTitle: "Another Error Title", alertMessage: "Another error message.")
            default:
                // Do other stuff
            }
        }       
    }
}

/**
 Utility method to display a single alert with an OK button.
 */
func displayAlert(alertTitle: String, alertMessage: String) {
    let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
    let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(okAction)
    self.present(alertController, animated: false, completion: nil)
}

我试过的

我尝试在我的 displayAlert 函数前面添加 @objc 并在异步块中像这样调用警报函数:

self.performSelector(onMainThread: #selector(ViewController.displayAlert(alertTitle: "Error Title", alertMessage: "Error Message")), with: self, waitUntilDone: false)

但我在编译器中遇到此错误:

Use of instance member 'displayAlert' on type 'ViewController'; did you mean to use a value of type 'ViewController' instead?

非常感谢关于我的错误所在的任何建议。感谢阅读。

我走在正确的道路上,但我使用的语法不正确(通常)。当我调用警报函数时,它会在主线程上执行操作,这意味着我需要获取主线程。

以下是我在异步块中调用警报的方式:

// ** This gets the main queue **
DispatchQueue.main.async(execute: {
    self.displayAlert(alertTitle: "Another Error Title", alertMessage: "Another error message.")
}

这是成品的样子:

let queue = DispatchQueue(label: "com.adrianbindc.myApp.myFunction")

queue.async {
    self.createArray()

    switch self.arrayIsEmpty() {
    case true:
        // ** This gets the main queue **
        DispatchQueue.main.async(execute: {
            self.displayAlert(alertTitle: "Error Title", alertMessage: "error message.")
        })

    case false:
        switch resultArray.count {
        case 0:
            // ** This gets the main queue **
            DispatchQueue.main.async(execute: {
                self.displayAlert(alertTitle: "Another Error Title", alertMessage: "Another error message.")
            })
        default:
            // Do other stuff
        }
    }
}

让我完成了终点线,并且有更多场景可能对 Swift 3.0 有帮助。