iosswiftnsurlnsurlsession

How do I get the data from an NSURLSession as a string?


I'm using an API that gives me data in a neat format - How do I get this as a String? I can print it, but saving it as a string doesn't seem to work.

I specifically want to update a UI element using the data from the NSURLSession task.

    let url = NSURL(string: apiCall)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        //I want to replace this line below with something to save it to a string.
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

    task.resume()

Solution

  • If your problem is that it is empty outside of the task, that is because it is going out of scope after the completion block ends. You need to save it somewhere that has a wider scope.

    let url = NSURL(string: apiCall)
    var dataString:String = ""
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        //I want to replace this line below with something to save it to a string.
        dataString = String(NSString(data: data, encoding: NSUTF8StringEncoding))
        dispatch_async(dispatch_get_main_queue()) {
            // Update the UI on the main thread.
            self.textView.text = dataString
        });
    
    }
    task.resume()
    

    now when you access dataString it will be set to the data from task. Be wary though, until task is completed, dataString won't be set, so you should really try to use it in the completion block.