Code after NSURLSession runs before session is over – Swift

By Jaxon

I have an app that accesses a website and downloads the HTML from that site, converts it to a string, grabs some information from the string, and then uses that for the app. My problem is that the code extracting the string runs before the data can actually be loaded. I tried putting that code in the completion handler, but that either didn’t fix the problem, or I did it wrong. Here is my code:

            let url = NSURL(string: "" + currentWord)
            var request: NSURLRequest = NSURLRequest(URL: url!)
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)
            let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
                if error == nil {
                    //Getting String From URL Data
                    let urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)!

The urlContent constant is assigned its value before the website data is loaded. I need a way to stop that from happening. I am fairly new to programing, so keep that in mind with your answer, thank you in advance.

Source: Stack Overflow


Share it with your friends!

    Fatal error: Uncaught Exception: 12: REST API is deprecated for versions v2.1 and higher (12) thrown in /home/content/19/9652219/html/wp-content/plugins/seo-facebook-comments/facebook/base_facebook.php on line 1273