Alamofire is a popular HTTP library for iOS and macOS, written in Swift and built on top of URLSession. It provides a declarative syntax for network requests, JSON handling, file uploads, and authentication management. According to the Alamofire GitHub repository (2025), Alamofire has over 42,000 stars and is used by thousands of iOS projects worldwide.
Key Takeaways
Alamofire is an HTTP client for Swift created by the Alamofire Software Foundation (originally by Mattt Thompson in 2014). The library abstracts low-level URLSession details, providing a clean and expressive API for network communication.
The core philosophy of Alamofire is chaining syntax where request parameters (URL, method, headers, parameters, encoder) are passed through sequential calls. This makes the code more readable and reduces the likelihood of errors related to incorrect URLRequest configuration. The declarative approach allows focusing on what needs to be done rather than the details of connection setup. The developer describes the desired result, and the library handles low-level network work.
The library has been actively maintained since 2014 and has gone through seven major versions. Alamofire 5, current as of 2025–2026, includes support for Combine, async/await, response converters, EventMonitor for debugging, and RequestInterceptor for intercepting requests. Each major version brought significant improvements: Alamofire 4 added Codable support, Alamofire 5 added Combine Publishers and an improved request interception system.
The Alamofire ecosystem includes additional libraries: AlamofireImage for image loading and caching, AlamofireNetworkActivityIndicator for the network indicator in the iOS status bar, and AlamofireObjectMapper for integration with ObjectMapper. These components make Alamofire a full-fledged network stack, not just an HTTP client.
Alamofire is installed via Swift Package Manager (recommended), CocoaPods, or Carthage. In Xcode, simply open the File → Add Packages menu, paste the repository URL, and specify the version.
// Swift Package Manager — add to Package.swift
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git",
from: "5.9.0")
]
// Import in file
import Alamofire
After installation, Alamofire is available globally through the AF namespace (short for Alamofire) without additional configuration. Most projects start by configuring a Session with their own settings — this allows setting a base URL, default headers, timeouts, and TLS certificate handlers.
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
let session = Session(configuration: configuration)
Creating a custom session through Session(configuration:) is necessary when a unique configuration is needed for different parts of the application — for example, a separate session for image downloads with aggressive caching and a separate one for API requests with authentication. The Alamofire Session accepts not only configuration but also an interceptor, serverTrustManager, cachedResponseHandler, and redirectHandler, providing full control over network behavior at all stages of the request.
Alamofire provides a wide range of functions covering most network interaction scenarios in iOS applications. Let's look at the key ones.
The basic request syntax includes the method, URL, parameters, and encoding. All standard HTTP methods are supported via the HTTPMethod enum: get, post, put, patch, delete. Parameters can be encoded as URL parameters (URLEncoding), JSON body (JSONEncoding), or multipart form data (MultipartFormData).
AF.request("https://api.example.com/users", method: .post,
parameters: ["name": "Alex", "role": "developer"])
.validate()
.responseDecodable(of: User.self) { response in
switch response.result {
case .success(let user):
print("Created by user: \(user)")
case .failure(let error):
print("Error: \(error)")
}
}
The validate() method automatically checks the status code (200–299) and content type, returning an error for unexpected responses, eliminating manual statusCode checking. responseDecodable uses the Decodable protocol for automatic JSON deserialization into Swift structures — this eliminates manual JSONSerialization and reduces boilerplate code when working with REST APIs.
Alamofire supports several response handler types: response (raw data), responseJSON (dictionary/array), responseString (text), responseData (Data), and responseDecodable (Decodable model). Response converters can be custom — for protobuf, graphic formats, or custom protocols.
For uploading data to the server, upload is used, supporting Data, File, and MultipartFormData. Downloading large files is done via download with the ability to resume through resumeData after connection interruption. Both operations support progress tracking through uploadProgress and downloadProgress with fractional values from 0 to 1 for display in the user interface.
Multipart upload with Alamofire is particularly convenient: the upload(multipartFormData:) method accepts a closure where form parts are added via append. Each part can contain data, a file, or a stream, as well as its own name and mime type. Alamofire automatically calculates multipart boundaries and sets the correct Content-Type header, saving the developer from manually forming the request body. For large files, it is recommended to use stream providers instead of loading the entire file into memory — this prevents memory limit exceedance on resource-constrained mobile devices. A typical scenario is sending a user avatar together with profile data in a single multipart request, which reduces the number of HTTP calls and simplifies server-side processing.
Comparing Alamofire with native URLSession helps make architectural decisions. Alamofire does not replace URLSession — it builds on top of it and uses the same configuration, caching, and background task mechanisms. All URLSession features are accessible through Alamofire, but with a more convenient declarative syntax.
| Criterion | Alamofire | URLSession |
|---|---|---|
| Syntax | Declarative, chaining | Imperative, closures |
| JSON Decoding | Automatic (responseDecodable) | Manual (JSONSerialization/JSONDecoder) |
| Validation | validate() — built-in | Manual statusCode check |
| Progress | uploadProgress, downloadProgress | Via URLSessionTaskDelegate |
| Interceptors | RequestInterceptor, EventMonitor | Delegates, subclasses |
| Dependencies | Requires installation (SPM, CocoaPods) | None, built into Foundation |
In large projects, Alamofire reduces network request code by 30–50% and simplifies error handling. In small projects or when binary size is a strict constraint, native URLSession is preferable due to the absence of external dependencies.
Modern Alamofire 5 integrates with Combine via the publishDecodable property, which returns a Publisher, allowing reactive request chains with error handling and data transformation. For async/await, methods with the value suffix are available — for example, AF.request(url).serializingDecodable(User.self).value, making the syntax extremely concise and reminiscent of working with native URLSession. When using async/await, closures are no longer needed, and error handling is done through standard Swift do-catch blocks, simplifying code maintenance and readability in the long term.
Let's look at a more complex example — a request with an interceptor that automatically adds an authorization token and performs a retry on a 401 error. This is a typical scenario for applications with JWT authentication.
class AuthInterceptor: RequestInterceptor {
func adapt(_ urlRequest: URLRequest,
for session: Session,
completion: @escaping (Result<URLRequest, Error>) -> Void) {
var request = urlRequest
request.setValue("Bearer \(TokenManager.shared.token)",
forHTTPHeaderField: "Authorization")
completion(.success(request))
}
func retry(_ request: Request,
for session: Session,
dueTo error: Error,
completion: @escaping (RetryResult) -> Void) {
guard let response = request.response,
response.statusCode == 401
else { return completion(.doNotRetry) }
TokenManager.shared.refreshToken { success in
completion(success ? .retry : .doNotRetry)
}
}
}
The AuthInterceptor implements two protocols: adapt (adds a token to each request) and retry (attempts to refresh the token on a 401 error). The retry method checks the response status code and, if a 401 is received, requests a new token via TokenManager. After a successful refresh, the request is automatically retried.
Using the interceptor with a session:
let session = Session(interceptor: AuthInterceptor())
session.request("https://api.example.com/profile")
.responseDecodable(of: Profile.self) { response in
print(response.result)
}
All requests through this session automatically pass through AuthInterceptor — the token is added to headers, and on a 401, a refresh and retry are performed. This eliminates authentication code duplication in every request and centralizes token management logic.
Frequently Asked Questions
Alamofire is a wrapper over URLSession with a declarative syntax, built-in validation, automatic JSON decoding, and interceptors. URLSession is Apple's native API without dependencies but requires more code for the same tasks. Alamofire reduces network code volume by 30–50%.
The recommended method is Swift Package Manager: in Xcode, select File → Add Packages, enter the URL https://github.com/Alamofire/Alamofire.git and specify version 5.9.0 or later. Alternatively, via CocoaPods: pod 'Alamofire', '~> 5.9'.
Yes, starting from Alamofire 5.5, async/await support was added. The request, upload, and download methods can be used with the await syntax. Alternatively, Alamofire integrates with Combine by publishing values through a Publisher.
Alamofire provides the uploadProgress and downloadProgress methods, which accept a closure with a Progress object. The progress returns fractionCompleted, completedUnitCount, and totalUnitCount, which is convenient for displaying in the UI via a progress bar.
Yes, Alamofire supports background sessions through the standard URLSessionConfiguration.background. You need to create a Session with the appropriate configuration and register a completion handler in AppDelegate. DownloadRequest will continue working even after the app is minimized.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also