Instantly share code, notes, and snippets.

Embed
What would you like to do?
Making HTTP Requests in Swift
//Uncomment both lines below if testing on an Xcode playground.
//import XCPlayground
//XCPSetExecutionShouldContinueIndefinitely()
let url = NSURL(string: "http://www.stackoverflow.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
@lteu

This comment has been minimized.

lteu commented Nov 11, 2014

does not work ....

@werne2j

This comment has been minimized.

werne2j commented Nov 11, 2014

Works for me

@hcri50

This comment has been minimized.

hcri50 commented Nov 30, 2014

does not work

@GLLefavi

This comment has been minimized.

GLLefavi commented Apr 9, 2015

You need to put it in a function to work, such as:

override func viewDidLoad() {
super.viewDidLoad()
test()
}

func test() {
    println("Start Test")
    let url = NSURL(string: "http://www.stackoverflow.com")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

    task.resume()
}
@fortmarek

This comment has been minimized.

fortmarek commented Sep 9, 2015

This works for me but for whatever reason, it doesn't work for this site: http://old.gjk.cz/suplovani.php
Any idea why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment