ios - Swift 闭包内更新的 UILabel 文本拒绝显示

标签 ios swift closures

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

代码使用“NSURLSession.sharedSession().dataTaskWithURL”闭包。虽然我能够正确获取数据并捕获“UILabel.text”中的相关文本,但我无法让实际的应用程序显示更新的 UILabel。

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

@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 更新

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

@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()
}

编辑

虽然这里并不重要,因为闭包没有被保留,但在某些情况下,explicitly declare capture lists to avoid retain cycles 很重要。 .

关于ios - Swift 闭包内更新的 UILabel 文本拒绝显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31116606/

相关文章:

ios - Firebase 崩溃报告 - 并非所有符号文件都已上传

ios - 注册 TableView 单元格时在 Swift 中使用 AnyClass

ios - 当用户编辑待处理的 Swift 3 时,防止 View 在 splitview 中消失

ios - adaptivePresentationStyleForPresentationController 在 6+ 上返回错误的 traitCollection

functional-programming - 如何在闭包中获取多个参数并打印它们?

ios - Swift - 从完成 block 中解散 View Controller

ios - 将 ViewController 的 View 分配给自定义 View 类不会显示自定义 View 属性

c++ - 如何使用 cocos2d-x v3.2 在全局类(helloworld.h)中声明标签?

ios - 为什么使 UIApplicationDelegate 中的 window 属性为可选而不是隐式解包可选?

c - 如何为 C 函数创建闭包