Site icon Treehouse Blog

Making a Network Request in Swift

To make a network request in Swift (read HTTP request), there are a couple of different ways of doing it – NSURL, NSURLRequest and NSURLSession. Since iOS 7, NSURLSession has been the preferred way of carrying out networking tasks let’s take a look at how we can download some data from a hypothetical site using NSURLSession and its associated classes. You can follow along quite easily by using an Xcode playground.

Given the string “http://www.thisisnotarealurl.com”, let’s start by creating an NSURL object.

let url = NSURL(string: "http://www.thisisnotarealurl.com")

Next, we need to create an NSURLSession singleton to manage our networking requests.

let session = NSURLSession.sharedSession()

With our session manager, we can now create a data task to make the HTTP request and grab data from the url.

let dataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response:NSURLResponse!, 
 error: NSError!) -> Void in
     //do something
 })

This isn’t a real url, of course, and we’re not expecting any data back, but if we were, we could access it in our completion handler using the data parameter. Similarly we can investigate the response object and any errors that we get back within the body of our completion handler as well. If you’ve been following along in an Xcode playground, the line of code we just added might not return any results (especially since our url is invalid) and that’s because dataTaskWithURL is an asynchronous call. To run asynchronous code in a playground, add the following lines of code to the top of your file

import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

This will allow you to use asynchronous code and get the results you are looking for.

And there you have it! A simple way to make an HTTP request in Swift. Now, while we only wrote a few lines of code, you might be unfamiliar with a lot of the terminology used in this post – singletons, session managers, asynchronous code, completion handlers and so on. Fret not! If you want to learn all this as well as how to use networking code in a real world app, check out the Build a Weather App in Swift course on Treehouse. If you are totally new to iOS and Swift development and need to start all the way at the beginning, we’ve also got an awesome iOS Development With Swift Track that assumes no prior knowledge.

Happy coding!

Exit mobile version