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.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Alamofire 5 Tutorial for iOS: Getting Started
30 mins
- Getting Started
- Using the SW API
- Understanding HTTP, REST and JSON
- Why Use Alamofire?
- Requesting Data
- Using a Codable Data Model
- Method Chaining
- Setting up Your Table View
- Updating the Detail View Controller
- Fetching Multiple Asynchronous Endpoints
- Creating a Data Model for Starships
- Fetching the Starship Data
- Updating Your Table View
- Sending Parameters With a Request
- Decoding Starships
- Searching for Ships
- Display a Ship’s List of Films
- Where to Go From Here?
Decoding Starships
Create a new Swift file in the Networking group. Name it Starships.swift and enter the following code:
struct Starships: Decodable {
var count: Int
var all: [Starship]
enum CodingKeys: String, CodingKey {
case count
case all = "results"
}
}
Like with Films
you only care about count
and results
.
Next, open MainTableViewController.swift and, after fetchFilms()
, add the following method for searching for starships:
func searchStarships(for name: String) {
// 1
let url = "https://swapi.dev/api/starships"
// 2
let parameters: [String: String] = ["search": name]
// 3
AF.request(url, parameters: parameters)
.validate()
.responseDecodable(of: Starships.self) { response in
// 4
guard let starships = response.value else { return }
self.items = starships.all
self.tableView.reloadData()
}
}
This method does the following:
- Sets the URL that you’ll use to access the starship data.
- Sets the key-value parameters that you’ll send to the endpoint.
- Here, you’re making a request like before, but this time you’ve added parameters. You’re also performing a
validate
and decoding the response intoStarships
. - Finally, once the request completes, you assign the list of starships as the table view’s data and reload the table view.
Executing this request results in a URL https://swapi.dev/api/starships?search={name}
where {name}
is the search query passed in.
Searching for Ships
Start by adding the following code to searchBarSearchButtonClicked(_:)
:
guard let shipName = searchBar.text else { return }
searchStarships(for: shipName)
This code gets the text typed into the search bar and calls the new searchStarships(for:)
method you just implemented.
When the user cancels a search, you want to redisplay the list of films. You could fetch it again from the API, but that’s a poor design practice. Instead, you’re going to cache the list of films to make displaying it again quick and efficient. Add the following property at the top of the class to cache the list of films:
var films: [Film] = []
Next, add the following code after the guard
statement in fetchFilms()
:
self.films = films.all
This saves away the list for films for easy access later.
Now, add the following code to searchBarCancelButtonClicked(_:)
:
searchBar.text = nil
searchBar.resignFirstResponder()
items = films
tableView.reloadData()
Here, you remove any search text entered, hide the keyboard using resignFirstResponder()
and reload the table view, which causes it to show films again.
Build and run. Search for wing. You’ll see all the ships with the word “wing” in their name or model.
That’s great! But, it’s not quite complete. If you tap one of the ships, the list of films that ship appears in is empty. This is easy to fix thanks to all the work you did before. There’s even a huge hint in the debug console!
Display a Ship’s List of Films
Open DetailViewController.swift and find fetchList()
. Right now, it only knows how to fetch the list associated with a film. You need to fetch the list for a starship. Add the following just before the default:
label in the switch
statement:
case is Starship:
fetch(data.listItems, of: Film.self)
This tells your generic helper to fetch a list of films for a given starship.
Build and run. Search for a starship. Select it. You’ll see the starship details and the list of films it appeared in.
You now have a fully functioning app! Congratulations.
Where to Go From Here?
You can download the completed project using the Download Materials button at the top or bottom of this article.
While building your app, you’ve learned a lot about Alamofire’s basics. You learned that Alamofire can make networking calls with very little setup and how to make basic calls using the request function by sending just the URL string.
Also, you learned to make more complex calls to do things like searching by sending parameters.
You learned how to use request chaining and request validation, how to convert the response into JSON and how to convert the response data into a custom data model.
This article covered the very basics. You can take a deeper dive by looking at the documentation on the Alamofire site at https://github.com/Alamofire/Alamofire.
I highly suggest learning more about Apple’s URLSession, which Alamofire uses under the hood:
I hope you enjoyed this tutorial. Please share any comments or questions about this article in the forum discussion below!