0

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 http://www.test.com and fetch the response:

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

import UIKit

var url : NSURL = NSURL(string: "http://www.test.com")!
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
    print("toto")
    if error != nil {
        print("error=\(error)")
        return
    } else {
        print("response = \(response!)")
        responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
        print("responseString = \(responseString)")
    }

});

task.resume()
print (responseString)

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

1 Answers1

4

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
jrturton
  • 118,105
  • 32
  • 252
  • 268