【问题标题】:Alamofire completionHandler updating ui works only when function finishesAlamofire completionHandler 更新 ui 仅在函数完成时有效
【发布时间】:2017-07-19 11:38:59
【问题描述】:

我使用 Alamofire 4.4。我在 Alamofire 的 completionHandler 中更新了 UI,但在函数完成之前它不会更新。我使用sleep(10) 进行测试。 UI 仅在 10 秒后更新。但我需要它在开始时更新。

很快。我在完成处理程序中执行了一些操作,这需要一些时间。大约10秒。我想显示过程完成的百分比。但是 UI 没有得到更新。例如:在流程标签的开头重命名为“Begin”在中心“Processing”在“Finish”。但标签仅在最后更改为“处理中”。

这是我的代码:

这是我的ViewController's viewDidLoad() 函数:

view.backgroundColor = UIColor.white

        label.frame = CGRect(x: 50, y: 50, width: 100, height: 20)
        label.text = "Begin"
        label.textColor = UIColor.black

        view.addSubview(label)

        Alamofire.request("http://google.com").responseData(completionHandler: {
            res in

            if let stCode = res.response?.statusCode {
                if stCode == 200 {
                    self.label.text = "Rename"

                    print("Rename")

                    // Here I do some processing. put sleep for test
                    sleep(10)

                    print("Should be modified 10 seconds earlier")
                }
            }
        })

我的标签文本仅在 10 秒后更改为“重命名”。我需要在一开始就改变它。

我的日志:

Rename (I need it to change here.)
Should be modified 10 seconds earlier (Here label changes after 10 seconds)

【问题讨论】:

  • 你的问题不清楚。
  • @SakirSherasiya 我编辑了我的问题。有什么不懂的告诉我
  • @BegmuhammetKakabayev 是否​​要在 10 秒后执行任何操作?
  • @SahilManchanda 很快。我在完成处理程序中执行了一些操作,这需要一些时间。大约10秒。我想显示过程完成的百分比。但是 UI 没有得到更新。例如:在流程标签的开头重命名为“Begin”在中心“Processing”在“Finish”。但标签仅在最后更改为“处理中”。

标签: ios swift3 alamofire


【解决方案1】:

根据 cmets 中的讨论 当 stCode == 200 然后执行你的下一行更改标签文本然后使用这个

DispatchQueue.global(qos: .background).async {
   ///perform your heavy task here(your 10 sec task)
  ///Upon completion of your task then in following queue    
    DispatchQueue.main.async {
        ///change your label text here of completion 
    }
}

【讨论】:

    【解决方案2】:

    UI操作必须在主线程上进行,所以使用

    DispatchQueue.main.async {
        self.label.text = "Rename"
    }
    

    【讨论】:

    • 我在某处读到 Alamofire completionHandler 在主线程上工作
    猜你喜欢
    • 2017-08-04
    • 2014-11-25
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多