[英]Swift xcode 6 label.text not changing in NSURLSession
This is a simple test app to demonstrate how to pull data from the web. 这是一个简单的测试应用程序,用于演示如何从Web提取数据。 Within it there is a
NSURLSession
which is triggered by a button action. 其中有一个
NSURLSession
,它由按钮动作触发。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var city: UITextField!
@IBOutlet weak var message: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
var urlString = "http://www.weather-forecast.com/locations/" + city.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))
var contentArray = urlContent!.componentsSeparatedByString("<span class=\"phrase\">")
var newContentArray = contentArray[1].componentsSeparatedByString("</span>")
var messageContent = newContentArray[0] as String
println(messageContent)
self.message.text = messageContent
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The problem is the label "message" wont change to the "messageContent" variable. 问题是标签“message”不会改变为“messageContent”变量。 When I
println(messageContent)
it displays the data perfectly in the console but the GUI label remains unchanged. 当我
println(messageContent)
它在控制台中完美地显示数据,但GUI标签保持不变。
If you place self.message.text = "it worked"
outside of the NSURLSession the label changes. 如果你在
self.message.text = "it worked"
之外放置self.message.text = "it worked"
working”,标签就会改变。
It seems to me that the problem occurs within the NSURLSession
not being able to change the label.text
在我看来,问题发生在
NSURLSession
无法更改label.text
Could someone please help? 有人可以帮忙吗?
NSURLSession's completion closure is invoked in sub thread. NSURLSession的完成关闭在子线程中调用。 Updating UI should be done in main thread.
更新UI应该在主线程中完成。
try this: 尝试这个:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.message.text = messageContent
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.