This application changes the autorun mechanism from the background thread swift2.0

I use this simple code to extract some plain text from a website.

@IBAction func askWeather(sender: AnyObject) { let url = NSURL(string: "http://www.weather-forecast.com/locations/" + userField.text! + "/forecasts/latest")! let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in if let urlContent = data{ let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding) let wArray = webContent?.componentsSeparatedByString("Day Weather Forecast Summary:</b><span class=\"read-more-small\"><span class=\"read-more-content\"> <span class=\"phrase\">") let wCont = wArray![1].componentsSeparatedByString("</span>") self.weatherResult.text = wCont[0] } else{ print("Sorry could not get weather information") } } task.resume() } @IBOutlet var weatherResult: UILabel! @IBOutlet var userField: UITextField! 

And after I press the button to get the information, nothing happens for several seconds (for example, 10-20), and then I get the correct result, however I get this message in xcode:

 This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release. 

I tried reading some posts on others having this problem, but they used streams like async etc. to run your code. I'm not quite sure what the problem is in my case.

Thanks!

0
source share
2 answers

I assume that self.weatherResult.text = wCont[0] changes something like UILabel or similar, in which case you are trying to change part of your user interface from a background thread - big no-no.

Try using this code instead:

 dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.weatherResult.text = wCont[0] } 
+2
source
  let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in 

There is your asynchronous stream. Right there. dataTaskWithURL runs in the background and ultimately calls the callback function that you passed. And it runs in the background.

+2
source

Source: https://habr.com/ru/post/1243924/


All Articles