Make an HTTP request

 Problem

I want to make a synchronous HTTP request, given a target URL.



 Recipe


// Set the URL where we're making the request

let request = NSURLRequest(URL: NSURL(string: "http://iswift.org")!)
do {
    // Perform the request
    var response : AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
    let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response)
    
    // Get data as string
    let str = NSString(data: data, encoding: NSUTF8StringEncoding)
    print(str)
}
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")
}

				

Heard the news?

The Swift Cookbook for Swift 3 is at last here! For iBooks, Kindle and Paperback.
Hurry up - and Check it out! ;-)

 

 Playground