Alamofire请求后,我是否需要DispatchQueue.main来更新UI? [英] Do I need DispatchQueue.main to update UI after an Alamofire request?

查看:180
本文介绍了Alamofire请求后,我是否需要DispatchQueue.main来更新UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注有关处理 REST / Web请求的教程。在本教程中,我们正在努力开发一个Pokedex应用程序,在该应用程序中,我们使用 Alamofire 从API中获取Pokemon详细信息,然后在用户界面中显示该数据。



以下是相关代码:

  typealias DownloadComplete =(Bool)-> ()

//模型类
func downloadPokemonDetails(已完成:@escaping DownloadComplete)
{
Alamofire.request(_pokemonURL).responseJSON {(response)in
var成功=真
如果让jsonData = response.result.value为?字典< String,Any>
{
//在此处解析json
...
}
否则
{
成功=假
}
完成(成功)
}
}

//控制器类
覆盖func viewDidLoad(){
super.viewDidLoad()
pokemon.downloadPokemonDetails(已完成:{(成功)在
中,如果成功
{
self.updateUI()
}
否则
{
print(失败:解析JSON数据)
}
})
}

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

现在我的问题是:我们不应该使用 DispatchQueue.main。和更新

  pokemon.downloadPokemonDetails(已完成:{(如果成功$ b,则在
中成功)) $ b {
DispatchQueue.main.async {
self.updateUI()
}
}

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

解决方案

如果不想阅读整个评论部分,我将其发布在此处作为答案。
首先,请阅读



** 在Xcode 9.1版(9B55)中演示


I'm following a tutorial about working with REST/web requests. In the tutorial, we're working towards a Pokedex app where we fetch Pokemon details from an API using Alamofire, and then displaying that data in our UIs.

Here's the related code:

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
}

Now my question is: shouldn't we use DispatchQueue.main. and update the UI there like so?

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

The tutorial left it out and I'm not sure if DispatchQueue is needed here to update the UI. I know that updating UI in a background thread is bad practice so if anyone can shed some light on whether using DispatchQueue here to get the main thread is necessary or not, I would very much appreciate it.

解决方案

If one does not want to read the whole comments section, I am posting here it as answer. Firstly, read Alamofire docs, which clearly states: "Response handlers by default are executed on the main dispatch queue."

It means, you can call any UI related code in response block. If you still feel uncomfortable to rely on 3rd party lib doc, you can check by executing this swift3 snippet:

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

xcode 9

Starting from xcode 9 there is a built-in Main Thread Checker which detects invalid use of AppKit, UIKit, and other APIs from a background thread. Main Thread Checker is automatically enabled when you run your app with the Xcode debugger.

If any part of your project contains invalid UI calls from background thread, you will see the following:

** Demonstrated in Xcode Version 9.1 (9B55)

这篇关于Alamofire请求后,我是否需要DispatchQueue.main来更新UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆