Alamofire 5 Tutorial for iOS: Getting Started

In this Alamofire tutorial, you’ll build an iOS companion app to perform networking tasks, send request parameters, decode/encode responses and more. By Corey Davis.

4.6 (54) · 3 Reviews

Download materials
Save for later
Share

If you’ve been developing iOS apps for some time, you’ve probably needed to access data over the network. And for that you may have used Foundation’s URLSession. This is fine and all, but sometimes it becomes cumbersome to use. And that’s where this Alamofire tutorial comes in!

Alamofire is a Swift-based, HTTP networking library. It provides an elegant interface on top of Apple’s Foundation networking stack that simplifies common networking tasks. Its features include chainable request/response methods, JSON and Codable decoding, authentication and more.

In this Alamofire tutorial, you’ll perform basic networking tasks including:

  • Requesting data from a third-party RESTful API.
  • Sending request parameters.
  • Converting the response into JSON.
  • Converting the response into a Swift data model via the Codable protocol.
Note: Before starting this tutorial, you should have a conceptual understanding of HTTP networking. Some exposure to Apple’s networking classes is helpful, but not necessary. Alamofire obscures implementation details, but it’s good to have some background knowledge if you need to troubleshoot your network requests.

Getting Started

To kick things off, use the Download Materials button at the top or bottom of this article to download the begin project.

The app for this tutorial is StarWarsOpedia, which provides quick access to data about Star Wars films as well as the starships used in those films.

Start by opening StarWarsOpedia.xcworkspace inside the begin project.

Build and run. You’ll see this:

empty tableview with search bar at the top

It’s a blank slate now, but you’ll populate it with data soon!

Note: You’d normally integrate Alamofire using CocoaPods or another dependency manager. In this case, it’s pre-installed in your downloaded projects. For help integrating Alamofire into your projects using CocoaPods, see CocoaPods Tutorial for Swift: Getting Started.

Using the SW API

SW API is a free and open API that provides Star Wars data. It’s only updated periodically, but it’s a fun way to get to know Alamofire. Access the API at swapi.dev.

There are multiple endpoints to access specific data, but you’ll concentrate on https://swapi.dev/api/films and https://swapi.dev/api/starships.

For more information, explore the Swapi documentation.

Understanding HTTP, REST and JSON

If you’re new to accessing third-party services over the internet, this quick explanation will help.

HTTP is an application protocol used to transfer data from a server to a client, such as a web browser or an iOS app. HTTP defines several request methods that the client uses to indicate the desired action. For example:

  • GET: Retrieves data, such as a web page, but doesn’t alter any data on the server.
  • HEAD: Identical to GET, but only sends back the headers and not the actual data.
  • POST: Sends data to the server. Use this, for example, when filling a form and clicking submit.
  • PUT: Sends data to the specific location provided. Use this, for example, when updating a user’s profile.
  • DELETE: Deletes data from the specific location provided.

JSON stands for JavaScript Object Notation. It provides a straightforward, human-readable and portable mechanism for transporting data between systems. JSON has a limited number of data types to choose from: string, boolean, array, object/dictionary, number and null.

Back in the dark days of Swift, pre-Swift 4, you needed to use the JSONSerialization class to convert JSON to data objects and vice-versa.

It worked well and you can still use it today, but there’s a better way now: Codable. By conforming your data models to Codable, you get nearly automatic conversion from JSON to your data models and back.

REST, or REpresentational State Transfer, is a set of rules for designing consistent web APIs. REST has several architecture rules that enforce standards like not persisting states across requests, making requests cacheable and providing uniform interfaces. This makes it easy for app developers to integrate the API into their apps without having to track the state of data across requests.

HTTP, JSON and REST comprise a good portion of the web services available to you as a developer. Trying to understand how every piece works can be overwhelming. That’s where Alamofire comes in.

Why Use Alamofire?

You may be wondering why you should use Alamofire. Apple already provides URLSession and other classes for accessing content via HTTP, so why add another dependency to your code base?

The short answer is that while Alamofire is based on URLSession, it obscures many of the difficulties of making networking calls, freeing you to concentrate on your business logic. You can access data on the internet with little effort, and your code will be cleaner and easier to read.

There are several major functions available with Alamofire:

  • AF.upload: Upload files with multi-part, stream, file or data methods.
  • AF.download: Download files or resume a download already in progress.
  • AF.request: Other HTTP requests not associated with file transfers.

These Alamofire methods are global, so you don’t have to instantiate a class to use them. Underlying Alamofire elements include classes and structs like SessionManager, DataRequest and DataResponse. However, you don’t need to fully understand the entire structure of Alamofire to start using it.

Enough theory. It’s time to start writing code!

Requesting Data

Before you can start making your awesome app, you need to do some setup.

Start by opening MainTableViewController.swift. Under import UIKit, add the following:

import Alamofire

This allows you to use Alamofire in this view controller. At the bottom of the file, add:

extension MainTableViewController {
  func fetchFilms() {
    // 1
    let request = AF.request("https://swapi.dev/api/films")
    // 2
    request.responseJSON { (data) in
      print(data)
    }
  }
}

Here’s what’s happening with this code:

  1. Alamofire uses namespacing, so you need to prefix all calls that you use with AF. request(_:method:parameters:encoding:headers:interceptor:) accepts the endpoint for your data. It can accept more parameters, but for now, you’ll just send the URL as a string and use the default parameter values.
  2. Take the response given from the request as JSON. For now, you simply print the JSON data for debugging purposes.

Finally, at the end of viewDidLoad(), add:

fetchFilms()

This triggers the Alamofire request you just implemented.

Build and run. At the top of the console, you’ll see something like this:

success({
  count = 7;
  next = "<null>";
  previous = "<null>";
  results =  ({...})
})

In a few very simple lines, you’ve fetched JSON data from a server. Good job!