加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift开发笔记19 在网络请求结束后更新UI

发布时间:2020-12-14 01:29:11 所属栏目:百科 来源:网络整理
导读:更新 UI 是必须回到主线程的 , 如果你是在网络请求的子线程中做操作,然后想更新 UI 的操作,那么需要把更新操作加入主队列 , 主队列的任务都是在主线程中执行的,这时需要用到GCD技术。 一般只需要这样写就可以 dispatch_async(dispatch_get_global_queue(D

更新UI是必须回到主线程的,如果你是在网络请求的子线程中做操作,然后想更新UI的操作,那么需要把更新操作加入主队列,主队列的任务都是在主线程中执行的,这时需要用到GCD技术。

一般只需要这样写就可以

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{
            //需要长时间处理的代码
            dispatch_async(dispatch_get_main_queue(),{
                //需要主线程执行的代码
            })
})
参考: http://www.starming.com/index.php?v=index&view=24

其实只要用这个异步回调主线程就可以:


dispatch_async(dispatch_get_main_queue(),{
//dosomething
self . orgnameLabel . text = " 测试 "
})

如果不这样会报异常:This application is modifying the autolayout engine from a background thread,which can lead to engine corruption and weird crashes. This will cause an exception in a future release.

并且更新UI不成功。
完整例子:

    @IBAction func click(sender: AnyObject) {
        
        self.imageView.image = nil
        
        let imgkURL = NSURL(string : STR_URL)
        
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        
        dispatch_async(dispatch_get_global_queue(priority,{
            
            let imgData = NSData(contentsOfURL : imgkURL!)
            let img = UIImage(data : imgData!)
            
            dispatch_async(dispatch_get_main_queue(),{
                self.imageView.image = img
            })
        })

    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读