Updated 12 days ago | GitHub
On this page

Network Programming

Many iOS applications are clients of a REST API. This guide gives an
overview of common ways to accomplish tasks associated with making
HTTP requests and handling responses. Low level socket programming,
although possible to do in iOS is out of the scope of this guide.

There is a wide variety of ways to make HTTP requests in iOS with which
you might at least want to be familiar.

NSURLConnection is a lower level mechanism
to make URL requests and is part of Apple’s Foundation Framework.

  • simplest way to make URL request
  • provides synchronous and asynchronous requests via completion
    handler blocks and delegates
  • does not have much support for authentication or a session concept
  • does not have an “operation” or “task” concept associated with
    requests so there’s no convenient way to handle queue of requests or
    to pause/resume
  • does not handle parsing of common content types
  • not much built in support for HTTP error codes / request parameters

NSURLSession is a higher level library that is part
of Apple’s Foundation Framework.

  • a replacement for the deprecated NSURLConnection (deprecated in iOS 9)
  • better support for authentication and has a session concept
  • concept of “task” enables pausing/resuming requests
  • can perform requests while your app is in the background
  • does not handle parsing of common content types
  • not much built in support for HTTP error codes / request parameters

AFNetworking was historically the most popular networking library for iOS. Note: AFNetworking was deprecated in January 2023 with no further releases planned. For new projects, Alamofire is the recommended replacement.

  • built on top of NSURLSession
  • built-in support for parsing common content-types
  • great support for common HTTP operations including handling of request
    params, headers, error codes
  • great integration with UIKit components making complex behavior like
    loading remote images asynchronously very easy

Alamofire is another networking library by the same
author as AFNetworking. It is written in Swift.

  • Swift only
  • many of the same features as AFNetworking
  • easy to use/read syntax for making common requests
  • no integration with UIKit

A note about threading and network requests

In iOS much of the code that runs in your application is triggered by an
event on the main event loop. The main event loop is
responsible for executing code to respond to things like user
interaction (e.g triggering an @IBAction) or events in a view
controller’s lifecycle (e.g. viewDidLoad). Code executed from the
main event loop is run on the main thread. This is convenient for us
because any updates to an application’s UI elements must happen on the
main thread
. We’ll want to keep this rule in mind when working with
network requests.

iOS provides a couple of higher level libraries for concurrent
programming: Grand Central Dispatch and
NSOperationQueue. You’ll be able to use either to
ensure that a piece of code does or does not run on the main thread.

You should never make a synchronous network request on the main thread
since this will block the thread and the UI will appear frozen while our
request is pending. You’ll rarely run into instances where you’ll need
to make synchronous requests.

When we make an asynchronous request, any of the above libraries will
execute the request on a background (i.e. not the main) thread. Some
methods will allow us to specify the dispatch queue on which we want the
response handler to run, others will provide no guarantees. If we
need to update the UI in our response handler we must ensure that the
code that manipulates the UI is run on the main thread.
This can be
tricky because we may call into a method that calls into another method
that after a long stack of calls eventually updates a UI element.

One simple way to ensure a block of code is run on the main thread using
Grand Central Dispatch is as follows

dispatch_async(dispatch_get_main_queue(), ^{
  // this code will be executed on the main thread
});
DispatchQueue.main.async {  
  // This code will be executed on the main thread
}  

Making a GET and parsing a JSON response

In order to provide you with the flavor of each of the major ways of
making network requests we discussed above, we’ll go through an example of each one that still compiles today.

NSURLConnection (deprecated in iOS 9)

NSURLConnection was the completion-handler API that predated URLSession. It was deprecated in iOS 9, and the pre-Swift-3 example that used to live here no longer compiles in current Swift toolchains, so it has been removed — use URLSession (next section) for all new code.

URLSession

URLSession is now the preferred built-in method of performing network requests on iOS.

Swift

class Movie {

    // ... 

    class func fetchMovies(successCallBack: @escaping (NSDictionary) -> (), errorCallBack: ((Error?) -> ())?) {
        let apiKey = "Put_Your_Client_Id_Here"
        let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)")!
        let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
        let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
        let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            if let error = error {
                errorCallBack?(error)
                return
            }
            guard let data = data else {
                errorCallBack?(nil)
                return
            }
            do {
                if let dataDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
                    //print(dataDictionary)
                    successCallBack(dataDictionary)
                } else {
                    // The response was valid JSON, but not a JSON object
                    errorCallBack?(nil)
                }
            } catch {
                // The response wasn't valid JSON
                errorCallBack?(error)
            }
        }
        task.resume()
    }
    // ...
}

Objective-C

NSString *apiKey = @"Put_Your_Client_Id_Here";
NSString *urlString =
[@"https://api.themoviedb.org/3/movie/now_playing?api_key=" stringByAppendingString:apiKey];

NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSession *session =
[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                              delegate:nil
                         delegateQueue:[NSOperationQueue mainQueue]];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData * _Nullable data,
                                                            NSURLResponse * _Nullable response,
                                                            NSError * _Nullable error) {
                                            if (!error) {
                                                NSError *jsonError = nil;
                                                NSDictionary *responseDictionary =
                                                [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                  error:&jsonError];
                                                NSLog(@"Response: %@", responseDictionary);
                                            } else {
                                                NSLog(@"An error occurred: %@", error.description);
                                            }
                                        }];
[task resume];

Codable

Codable is Apple’s latest powerful contribution to efforts to better improve the built-in networking libraries available to iOS and Mac OS engineers. Codable is actually a typealias for Encodable and Decodable protocols that allows you to quickly decode and encode external representations (such as JSON strings) as native Structs in Swift.
Before Codable was introduced to the Swift language in Swift 4, many developers had to rely on third party frameworks or building their own JSON decoding code which required a lot of boilerplate code. However, with the introduction of Codable, it’s actually really easy to write 100% Swift networking code! Let’s give it a try!

Let’s assume you are implementing a movie list viewing application that shows the movies returned by the TMDB “Now Playing” endpoint used in the URLSession example above. Its JSON response looks like this (abridged — each result carries more fields than shown here):

{
    "dates": {
        "maximum": "2023-05-03",
        "minimum": "2023-03-16"
    },
    "page": 1,
    "results": [
        {
            "adult": false,
            "id": 502356,
            "original_language": "en",
            "poster_path": "/qNBAXBIQlnOThrVvA6mA2B5ggV6.jpg",
            "release_date": "2023-04-05",
            "title": "The Super Mario Bros. Movie",
            "vote_average": 7.5,
            "vote_count": 1456
        }
    ],
    "total_pages": 87,
    "total_results": 1734
}

With the power of Codable, you can implement a native Struct object with the following code.

struct MovieResponse: Codable {
    let page: Int
    let totalResults: Int
    let films: [Film]

    enum CodingKeys: String, CodingKey {
        case page
        case totalResults = "total_results"
        case films = "results"
    }
}

struct Film: Codable {
    let id: Int
    let title: String
    let posterPath: String? // Optional, in case a movie has no poster
    let score: Double

    enum CodingKeys: String, CodingKey {
        case id, title
        case posterPath = "poster_path"
        case score = "vote_average"
    }
}

As you can see, the Struct looks almost exactly like you would want it to look if you were using it to drive a UITableViewDataSource or a custom film details View Controller.
When a type declares a nested CodingKeys enum conforming to CodingKey, its cases are the authoritative list of properties that get encoded and decoded, so the structs only need to declare the fields the app uses — keys such as dates and vote_count are not read. Can you guess why some cases have a declared raw value? If you’re thinking it’s related to Snake Case, you’re right! When the keys in the JSON don’t match your property names, you give the CodingKeys enum String raw values, and each raw value is the key name used during encoding and decoding. That lets you name properties according to the Swift API Design Guidelines (posterPath, totalResults) instead of copying the API’s poster_path and total_results, or even pick a different name altogether: films reads TMDB’s results array, and score reads vote_average.
Note that poster_path is only the end of an image URL. To build the full URL, TMDB’s image basics guide combines a base URL and size from its /configuration API with the path, for example https://image.tmdb.org/t/p/w500/1E5baAaEse26fej7uHcjOgEE2t2.jpg.
So how do we use it? Easy!
Let’s go back to the example from URLSession, and instead of a general NSDictionary (which would require a lot more code on the consumption side like a MovieObject class with init(fromDict dict: NSDictionary) in order to be usable in your code base), let’s substitute it with our Codable compatible struct.

class Movie {

    // ... 

    class func fetchMovies(successCallBack: @escaping ([Film]?) -> (), errorCallBack: ((Error?) -> ())?) {
        let apiKey = "Put_Your_Client_Id_Here"
        let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)")!
        let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
        let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
        let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            if let error = error {
                errorCallBack?(error)
                return
            }
            guard let data = data else {
                errorCallBack?(nil)
                return
            }
            do {
                let filmResponse = try JSONDecoder().decode(MovieResponse.self, from: data)
                //print(filmResponse.films)
                successCallBack(filmResponse.films)
            } catch {
                // The JSON was invalid or didn't match MovieResponse
                errorCallBack?(error)
            }
        }
        task.resume()
    }
    // ...
}

It might not look like much, but a significant amount of code is saved from the Movie class object, and when you consume this API call, on the other side you’ll get the Film objects you need to drive your UI, rather than a Dictionary you’d have to iterate over, verifying each value.

On iOS 15 and later, URLSession also has an async method, data(from:delegate:), that returns the downloaded data and response instead of calling a completion handler. Because both it and JSONDecoder.decode(_:from:) throw, transfer errors and decoding errors both reach the caller as thrown errors, and there are no callbacks to forget to call:

class Movie {

    // ...

    @available(iOS 15.0, *)
    class func fetchMovies() async throws -> [Film] {
        let apiKey = "Put_Your_Client_Id_Here"
        let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)")!
        let (data, _) = try await URLSession.shared.data(from: url)
        let filmResponse = try JSONDecoder().decode(MovieResponse.self, from: data)
        return filmResponse.films
    }
    // ...
}

To call it from synchronous code such as viewDidLoad(), start a Task. A new Task runs with the same actor isolation as the code that creates it, and UIViewController is @MainActor, so a Task created in a view controller method can update the UI directly after the await:

override func viewDidLoad() {
    super.viewDidLoad()
    Task {
        do {
            let films = try await Movie.fetchMovies()
            // Update the UI with films
        } catch {
            print("Failed to fetch movies: \(error)")
        }
    }
}

Codable can save you a significant amount of time in writing networking code, and it’s growing in popularity, so I highly recommend picking it up!

AFNetworking

Note: AFNetworking was fully deprecated in January 2023 — prefer URLSession or Alamofire for new projects (see the deprecation note above). The Swift example that used to live here was written for AFNetworking 2.x’s AFHTTPRequestOperationManager (removed in AFNetworking 3.0) and no longer compiles, so only the Objective-C example remains.

The code below starts to look a little cleaner with AFNetworking.
AFNetworking does some error handling for us and gives us a way to
provide a failure handler. Also note that we no longer have to parse
the JSON result ourselves since AFNetworking does this automatically
based on the content type.

Objective-C

- (void)getNowPlaying:(void(^)(NSDictionary *))completion {

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"https://api.themoviedb.org/3/movie/now_playing?api_key=Put_Your_Client_Id_Here"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request
                                                   uploadProgress:nil
                                                 downloadProgress:nil
                                                completionHandler:^(NSURLResponse *response, id  responseObject, NSError *error) {
                                                        if (error) {
                                                            NSLog(@"Error: %@", error);
                                                        } else {
                                                            NSLog(@"%@ %@", response, responseObject);
                                                            NSDictionary *dataDictionary = responseObject;
                                                            completion(dataDictionary);
                                                        }
                                                }];
    [dataTask resume];
}