在学习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的主线程就足够了:)
NSURLSession
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() }
编辑
尽管由于不保留闭包而在这里并不重要,但在某些情况下,显式声明捕获列表以避免保留周期很重要。