LearnMaking a Network Request in Swift


writes on October 9, 2014

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!


Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

4 Responses to “Making a Network Request in Swift”

  1. Proteus on April 18, 2016 at 9:37 am said:

    Hello, how would you execute a request to execute a PHP script on a remote server (using either GET or POST) when the app is in the __background__ (not used)? Thank you!

  2. Thank you, William!

    You will also want to set: NSAllowsArbitraryLoads (dictinary) key to YES under NSAppTransportSecurity dictionary in your .plist file. Hope this helps!

    To test with http links otherwise you will get: Transport security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app’s Info.plist file.

  3. William Heineman on August 17, 2015 at 12:37 pm said:

    You’re missing a key line of code. I spent hours trying to figure out why my request was never completing.

    After creating the dataTask, you have to tell it to execute:


  4. Hello Passan. I was wondering how you would do GET and POST requests. I have an api and was wondering how to interact with it

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop