laurent.lefevre laurent.lefevre - 1 year ago 101
Swift Question

swift 2 newbie : dataTaskWithRequest callback not executed?

i'm new to Swift, i allready learned the basic syntax and i'm trying to do more advanced stuff.
My first attempt with the code bellow is to do an HTTP request on the URL and fetch the response:

//: Playground - noun: a place where people can play

import UIKit

var url : NSURL = NSURL(string: "")!
var request: NSURLRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var responseString:NSString?;

let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if error != nil {
} else {
print("response = \(response!)")
responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print("responseString = \(responseString)")


print (responseString)

When i run the code in Xcode, "toto" isn't printed and responseString is nil, any idea on what's going wrong ?

Answer Source

You're running this in a playground, and you need to do a bit of extra work to get asynchronous tasks running.

First, import XCPlayground:

import XCPlayground

Then, at the end of the playground, add this line:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

This keeps the playground executing so it can wait around for your completion block to happen.

For Xcode 8:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download