在Swift闭包中更新的UILabel文本拒绝显示 [英] UILabel text updated inside a Swift closure refuses to show

查看:191
本文介绍了在Swift闭包中更新的UILabel文本拒绝显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习Swift时,我编写了一个简单的iOS应用程序,从一个网站抓取某个城市的天气信息,并将其显示在UILabel中。

While learning Swift, I am coding a simple practice iOS app to scrape weather info for a given city from a site and show it in a UILabel.

使用NSURLSession.sharedSession()。dataTaskWithURL闭包。虽然我能够正确获取数据并捕获相关文本在UILabel.text,我不能得到实际的应用程序显示更新的UILabel。

The code uses a "NSURLSession.sharedSession().dataTaskWithURL" closure. Although I'm able to fetch the data correctly and capture the relevant text in the "UILabel.text", I can't get the actual app to show the updated UILabel.

我做错了什么?以下是相关代码:

What am I doing wrong? Here is the relevant code:

@IBAction func buttonPressed(sender: AnyObject) {

   var urlString = "http://www.weather-forecast.com/locations/" + cityName.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"

   var url = NSURL(string: urlString)

   let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in

      var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as String

      var contentArray = urlContent.componentsSeparatedByString("<span class=\"phrase\">")
      var weatherInfo = contentArray[1].componentsSeparatedByString("</span>")

      self.resultShow.text = weatherInfo[0] // Text does not show in the app

      println(weatherInfo[0]) // This works correctly
      println(self.resultShow.text) // This works correctly

   }

   task.resume()

}


推荐答案

在主线程上执行UI更新

You need to perform your UI updates on the main thread

NSURLSession 完成处理程序将始终在后台线程上调用。要更新你的UI,一个简单的 dispatch_async 到主线程应该足够了:)

NSURLSession completion handlers will always be called on the background thread. To update your UI a simple dispatch_async to the main thread should suffice:)

@IBAction func buttonPressed(sender: AnyObject) {
   var urlString = "http://www.weather-forecast.com/locations/" + cityName.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"
   var url = NSURL(string: urlString)
   let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in

      var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as String

      var contentArray = urlContent.componentsSeparatedByString("<span class=\"phrase\">")
      var weatherInfo = contentArray[1].componentsSeparatedByString("</span>")

      dispatch_async(dispatch_get_main_queue(), {
          //perform all UI stuff here        
          self.resultShow.text = weatherInfo[0] 
      })
   }
   task.resume()
}

EDIT

,在某些情况下,重要的是显式声明捕获列表以避免保留周期

Whilst not important here since the closure is not retained, in some instances it's important to explicitly declare capture lists to avoid retain cycles.

这篇关于在Swift闭包中更新的UILabel文本拒绝显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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