在 Alamofire 请求后,我是否需要 DispatchQueue.main 来更新 UI?

Do I need DispatchQueue.main to update UI after an Alamofire request?

我正在学习有关使用 REST/web requests 的教程。在本教程中,我们正在开发一个 Pokedex 应用程序,我们使用 Alamofire 从 API 中获取口袋妖怪的详细信息,然后在我们的 UI 中显示该数据。

相关代码如下:

typealias DownloadComplete = (Bool) -> ()

// Model class
func downloadPokemonDetails(completed: @escaping DownloadComplete)
    {
        Alamofire.request(_pokemonURL).responseJSON { (response) in
            var success = true
            if let jsonData = response.result.value as? Dictionary<String, Any>
            {
                // parse the json here
                ...
            }
            else
            {
                success = false
            }
            completed(success)
        }
    }

// Controller class
override func viewDidLoad() {
        super.viewDidLoad()
        pokemon.downloadPokemonDetails(completed: { (success) in
            if success
            {
                self.updateUI()
            }
            else
            {
                print("FAILED: TO PARSE JSON DATA")
            }
        })
    }

func updateUI()
{
    attackLbl.text = pokemon.attack
    defenseLbl.text = pokemon.defense
    heightLbl.text = pokemon.height
    weightLbl.text = pokemon.weight
}

现在我的问题是:我们不应该使用 DispatchQueue.main. 并像这样更新 UI 吗?

pokemon.downloadPokemonDetails(completed: { (success) in
            if success
            {
                DispatchQueue.main.async {
                    self.updateUI()
                }
            }

教程遗漏了它,我不确定这里是否需要 DispatchQueue 来更新 UI。我知道在后台线程中更新 UI 是不好的做法,所以如果有人能阐明是否有必要在此处使用 DispatchQueue 来获取主线程,我将非常感激。

如果不想阅读整个评论部分,我将其张贴在这里作为答案。 首先,阅读Alamofire docs,其中明确指出:"Response handlers by default are executed on the main dispatch queue."

这意味着,您可以在响应块中调用任何UI相关代码。如果你仍然觉得依赖 3rd party lib doc 不舒服,你可以通过执行这个 swift3 片段来检查:

if Thread.isMainThread { 
   print("Main Thread") 
}

xcode 9

xcode 9开始有一个内置的Main Thread Checker检测AppKit、UIKit等的无效使用来自后台线程的 API。 Main Thread Checker 当您 运行 使用 Xcode 调试器的应用程序时自动启用。

如果项目的任何部分包含来自后台线程的无效 UI 调用,您将看到以下内容:

** 在 Xcode 版本 9.1 (9B55)

中演示