UILabel! is not updating properly

时间:2015-09-01 21:24:47

标签: ios xcode swift

My self.message.text = (newContentArray[0] as! String) is not letting me print to my label. My label is hooked up correctly, but it isn't loading up my data.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var city: UITextField!
    @IBOutlet weak var message: UILabel!

    @IBAction func buttonPressed(sender: AnyObject) {

        self.view.endEditing(true)

        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>")

            self.message.text = (newContentArray[0] as! String)

        }
        task.resume()
    }

1 个答案:

答案 0 :(得分:4)

You should update your UI on the main thread. inside the response block add this:

dispatch_async(dispatch_get_main_queue(),{ 
    var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)       
    var contentArray = urlContent!.componentsSeparatedByString("<span class=\"phrase\">") 
    var newContentArray = contentArray[1].componentsSeparatedByString("</span>") 
    self.message.text = (newContentArray[0] as! String) 
})