Alamofire简介:
Alamofire是AFN团队的Swift版本、是网络请求的开源库、目前有24588 star、目前支持Swift 3.0, 3.1, 3.2, and 4.0
译文如下:
Alamofire是一个使用Swift语言的网络开源库
- 特点
- 组成的库
- 要求
- 迁移指南
- 交流
- 安装
- 用法
- 介绍 - 进行网络请求, 响应操作, 响应校验, 响应缓存
- HTTP - HTTP 方式, Parameter 编码, HTTP Headers, 验证
- 数据上传下载 - 下载数据到文件, 上传数据到副服务器
- 工具 - Statistical Metrics, cURL Command Output
- 高级使用方法
- URL 会话 - 会话管理者, 会话代理, 请求
- Routing - Routing Requests, Adapting and Retrying Requests
- Model Objects - Custom Response Serialization
- Connection - 安全, 网络监测
- Open Radars
特点
- [x]链式请求、响应方法
- [x] URL / JSON / plist 参数编码
- [x] 上传文件、数据、流等多种类型
- [x] 文件下载与恢复下载
- [x] 使用URLCredential进行身份验证
- [x] HTTP Response 校验
- [x] 上传和下载进度
- [x] cURL Command Output
- [x] 动态设置、重试请求
- [x] TLS Certificate and Public Key Pinning
- [x] 网络连接监测
- [x] Comprehensive Unit and Integration Test Coverage
- [x] Complete Documentation
包含的库
为了保证Alamofire高度集中在网络处理部分,添加由 Alamofire Software Foundation 创建的组件库给Alamofire带来额外的功能。
- AlamofireImage - 图像库包含图片响应的一系列方法,它是
UIImage
andUIImageView
的扩展,提供常见的图片处理滤镜、一个自动清除内存缓存和基于优先级的图像下载系统。 - AlamofireNetworkActivityIndicator - 一个关于网络活动的指示器,它包含可配置延迟计时器来帮助减轻闪烁,可以支持不是由Alamofire管理“URLSession”实例。
要求
- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 8.1, 8.2, 8.3, and 9.0
- Swift 3.0, 3.1, 3.2, and 4.0
迁移指导
使用方法
一个简单的网络请求
import Alamofire
Alamofire.request("https://httpbin.org/get")
响应处理
在Alamofire中处理请求的响应,是被链式连接到请求之中的,也就是.
链接
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
在上面的请求中,responseJSON
操作将会在Request
之后执行,而不是通过block等待服务器的响应, callback这种闭包的形式是在收到信息后返回处理特定信息。我们必须在闭包之内完成想做的一切事情。
Networking in Alamofire is done asynchronously. 在这里你可以了解更多异步编程 的好处
Alamofire 默认包含五种不同的响应方式:
// Response Handler - Unserialized Response
func response(
queue: DispatchQueue?,
completionHandler: @escaping (DefaultDataResponse) -> Void)
-> Self
// Response Data Handler - Serialized into Data
func responseData(
queue: DispatchQueue?,
completionHandler: @escaping (DataResponse<Data>) -> Void)
-> Self
// Response String Handler - Serialized into String
func responseString(
queue: DispatchQueue?,
encoding: String.Encoding?,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
// Response JSON Handler - Serialized into Any
func responseJSON(
queue: DispatchQueue?,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
// Response PropertyList (plist) Handler - Serialized into Any
func responsePropertyList(
queue: DispatchQueue?,
completionHandler: @escaping (DataResponse<Any>) -> Void))
-> Self
没有响应操作处理任何来自服务器的HTTPURLResponse
的校验
例如:响应码为400到500之间、500到600之间,但是不自动做出错误标记。Alamofire通过Response Validation 方法链接实现上述。
response
响应操作
response
操作不做任何数据优化操作,仅仅是消息的传递、等价于使用cURL
执行请求
Alamofire.request("https://httpbin.org/get").response { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
我们非常希望你可以利用其它的响应系列来讨论响应和结果类型的优缺点
responseData
响应数据操作
responseData
使用responseDataSerializer
提取服务器返回的数据,如果没有错误而且数据被返回了,那么响应结果Result
应该是
.success
并且value
是Data
数据
Alamofire.request("https://httpbin.org/get").responseData { response in
debugPrint("All Response Info: \(response)")
if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
responseString
字符串响应处理
responseString
使用responseStringSerializer
提取服务器返回的数据为String
,并可以使用特定的编码,如果没有错误而且数据被返回为String
,那么响应结果Result
应该是.success
并且value
是String
数据
Alamofire.request("https://httpbin.org/get").responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
如果
String
编码没有被特殊指定,那么将使用来自服务器的HTTPURLResponse编码,如果服务器也无法提供,那么默认为.isoLatin1
responseJSON
响应处理
responseJSON
使用responseJSONSerializer
提取服务器返回的数据为Any
,使用JSONSerialization.ReadingOptions
,如果没有错误而且数据被返回为JSON
对象,那么响应结果Result
应该是
.success
并且value
是Any
类型
Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
}
}
所有的处理使用
JSONSerialization
API in theFoundation
framework
链接响应操作
响应操作连接:
Alamofire.request("https://httpbin.org/get")
.responseString { response in
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print("Response JSON: \(response.result.value)")
}
It is important to note that using multiple response handlers on the same
Request
requires the server data to be serialized multiple times. Once for each response handler.
响应线程
响应通常会默认在主线程、然而一个自定义的线程也可以使用
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in
print("Executing response handler on utility queue")
}
响应校验 Response Validation
通常,Alamofire对于任何完整地请求都回成功、并且不在乎响应的内容;在响应操作导致一个错误生成之前,如果一个响应有不被接受的状态码或者MIME类型,这就叫做验证
手动校验 Manual Validation
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
自动校验 Automatic Validation
Automatically validates status code within 200..<300
range, and that the Content-Type
header of the response matches the Accept
header of the request, if one is provided.
这段话的意思是:自动校验的状态码为:200-300、Content-Type
如果提供了就有
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
响应缓存 Response Caching
Response Caching is handled on the system framework level by URLCache
. It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions.
响应缓存由系统框架级别的URLCache
处理、他提供内存加磁盘混合缓存、并且你可以操控二者的分配大小
凡是以Alamofire.request开头的请求都是把数据加载进内存,那么为什么还要区分内存和硬盘呢?相对于比较小的数据,加载进内存是高效的,但对于比较大的文件,加载进内存确实灾难性的,因为很可能造成内存崩溃。因此,在处理大文件这个问题上,我们应该用Alamofire.download把数据保存到一个临时的本地文件中。
默认,Alamofire利用
URLCache
、为了定制他,你可以查看 Session Manager Configurations 部分
请求方法 HTTP Methods
HTTPMethod
枚举 你可以从这里查看详细信息 RFC 7231 §4.3:
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
这些值作为Alamofire.request
接口方法被传递
Alamofire.request("https://httpbin.org/get") // method defaults to `.get`
Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)
The
Alamofire.request
method parameter defaults to.get
.
默认是.get
参数编码 Parameter Encoding
Alamofire支持URL
, JSON
and PropertyList
三种类型编码,也支持一些符合编码协议的常用编码
URL 编码 URL Encoding
The URLEncoding
type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the Destination
of the encoding. The Destination
enumeration has three cases:
.methodDependent
- Applies encoded query string result to existing query string forGET
,HEAD
andDELETE
requests and sets as the HTTP body for requests with any other HTTP method..queryString
- Sets or appends encoded query string result to existing query string..httpBody
- Sets encoded query string result as the HTTP body of the URL request.
The Content-Type
HTTP header field of an encoded request with HTTP body is set to application/x-www-form-urlencoded; charset=utf-8
. Since there is no published specification for how to encode collection types, the convention of appending []
to the key for array values (foo[]=1&foo[]=2
), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz
).
GET Request With URL-Encoded Parameters
let parameters: Parameters = ["foo": "bar"]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default`
Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent))
// https://httpbin.org/get?foo=bar
POST Request With URL-Encoded Parameters
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
JSON Encoding
The JSONEncoding
type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The Content-Type
HTTP header field of an encoded request is set to application/json
.
POST Request with JSON-Encoded Parameters
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
// Both calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
Property List Encoding
The PropertyListEncoding
uses PropertyListSerialization
to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The Content-Type
HTTP header field of an encoded request is set to application/x-plist
.
Custom Encoding
In the event that the provided ParameterEncoding
types do not meet your needs, you can create your own custom encoding. Here’s a quick example of how you could build a custom JSONStringArrayEncoding
type to encode a JSON string array onto a Request
.
struct JSONStringArrayEncoding: ParameterEncoding {
private let array: [String]
init(array: [String]) {
self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
let data = try JSONSerialization.data(withJSONObject: array, options: [])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
return urlRequest
}
}
Manual Parameter Encoding of a URLRequest
The ParameterEncoding
APIs can be used outside of making network requests.
let url = URL(string: "https://httpbin.org/get")!
var urlRequest = URLRequest(url: url)
let parameters: Parameters = ["foo": "bar"]
let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
HTTP Headers
Adding a custom HTTP header to a Request
is supported directly in the global request
method. This makes it easy to attach HTTP headers to a Request
that can be constantly changing.
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
debugPrint(response)
}
For HTTP headers that do not change, it is recommended to set them on the
URLSessionConfiguration
so they are automatically applied to anyURLSessionTask
created by the underlyingURLSession
. For more information, see the Session Manager Configurations section.
The default Alamofire SessionManager
provides a default set of headers for every Request
. These include:
Accept-Encoding
, which defaults togzip;q=1.0, compress;q=0.5
, per RFC 7230 §4.2.3.Accept-Language
, which defaults to up to the top 6 preferred languages on the system, formatted likeen;q=1.0
, per RFC 7231 §5.3.5.User-Agent
, which contains versioning information about the current app. For example:iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0
, per RFC 7231 §5.5.3.
If you need to customize these headers, a custom URLSessionConfiguration
should be created, the defaultHTTPHeaders
property updated and the configuration applied to a new SessionManager
instance.
Authentication
Authentication is handled on the system framework level by URLCredential
and URLAuthenticationChallenge
.
Supported Authentication Schemes
HTTP Basic Authentication
The authenticate
method on a Request
will automatically provide a URLCredential
to a URLAuthenticationChallenge
when appropriate:
let user = "user"
let password = "password"
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.responseJSON { response in
debugPrint(response)
}
Depending upon your server implementation, an Authorization
header may also be appropriate:
let user = "user"
let password = "password"
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers)
.responseJSON { response in
debugPrint(response)
}
Authentication with URLCredential
let user = "user"
let password = "password"
let credential = URLCredential(user: user, password: password, persistence: .forSession)
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(usingCredential: credential)
.responseJSON { response in
debugPrint(response)
}
It is important to note that when using a
URLCredential
for authentication, the underlyingURLSession
will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which “may” trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlyingURLSession
.
Downloading Data to a File
Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The Alamofire.request
APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it’s more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the Alamofire.download
APIs to download the server data to a temporary file on-disk.
This will only work on
macOS
as is. Other platforms don’t allow access to the filesystem outside of your app’s sandbox. To download files on other platforms, see the Download File Destination section.
Alamofire.download("https://httpbin.org/image/png").responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
The
Alamofire.download
APIs should also be used if you need to download data while your app is in the background. For more information, please see the Session Manager Configurations section.
Download File Destination
You can also provide a DownloadFileDestination
closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the destinationURL
, the DownloadOptions
specified in the closure will be executed. The two currently supported DownloadOptions
are:
.createIntermediateDirectories
- Creates intermediate directories for the destination URL if specified..removePreviousFile
- Removes a previous file from the destination URL if specified.
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to: destination).response { response in
print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
}
}
You can also use the suggested download destination API.
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download("https://httpbin.org/image/png", to: destination)
Download Progress
Many times it can be helpful to report download progress to the user. Any DownloadRequest
can report download progress using the downloadProgress
API.
Alamofire.download("https://httpbin.org/image/png")
.downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
The downloadProgress
API also takes a queue
parameter which defines which DispatchQueue
the download progress closure should be called on.
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.download("https://httpbin.org/image/png")
.downloadProgress(queue: utilityQueue) { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
Resuming a Download
If a DownloadRequest
is cancelled or interrupted, the underlying URL session may generate resume data for the active DownloadRequest
. If this happens, the resume data can be re-used to restart the DownloadRequest
where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request.
IMPORTANT: On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3),
resumeData
is broken on background URL session configurations. There’s an underlying bug in theresumeData
generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow post.
class ImageRequestor {
private var resumeData: Data?
private var image: UIImage?
func fetchImage(completion: (UIImage?) -> Void) {
guard image == nil else { completion(image) ; return }
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
let request: DownloadRequest
if let resumeData = resumeData {
request = Alamofire.download(resumingWith: resumeData)
} else {
request = Alamofire.download("https://httpbin.org/image/png")
}
request.responseData { response in
switch response.result {
case .success(let data):
self.image = UIImage(data: data)
case .failure:
self.resumeData = response.resumeData
}
}
}
}
Uploading Data to a Server
When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the Alamofire.request
APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an InputStream
, then the Alamofire.upload
APIs are what you want to use.
The
Alamofire.upload
APIs should also be used if you need to upload data while your app is in the background. For more information, please see the Session Manager Configurations section.
Uploading Data
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
Uploading a File
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
Uploading Multipart Form Data
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(unicornImageURL, withName: "unicorn")
multipartFormData.append(rainbowImageURL, withName: "rainbow")
},
to: "https://httpbin.org/post",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
Upload Progress
While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any UploadRequest
can report both upload progress and download progress of the response data using the uploadProgress
and downloadProgress
APIs.
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL, to: "https://httpbin.org/post")
.uploadProgress { progress in // main queue by default
print("Upload Progress: \(progress.fractionCompleted)")
}
.downloadProgress { progress in // main queue by default
print("Download Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
debugPrint(response)
}
Statistical Metrics
Timeline
Alamofire collects timings throughout the lifecycle of a Request
and creates a Timeline
object exposed as a property on all response types.
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.timeline)
}
The above reports the following Timeline
info:
Latency
: 0.428 secondsRequest Duration
: 0.428 secondsSerialization Duration
: 0.001 secondsTotal Duration
: 0.429 seconds
URL Session Task Metrics
In iOS and tvOS 10 and macOS 10.12, Apple introduced the new URLSessionTaskMetrics APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the Timeline
, but provides many more statistics that Alamofire doesn’t have access to compute. The metrics can be accessed through any response type.
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.metrics)
}
It’s important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks:
Alamofire.request("https://httpbin.org/get").responseJSON { response in
if #available(iOS 10.0, *) {
print(response.metrics)
}
}
cURL Command Output
Debugging platform issues can be frustrating. Thankfully, Alamofire Request
objects conform to both the CustomStringConvertible
and CustomDebugStringConvertible
protocols to provide some VERY helpful debugging tools.
CustomStringConvertible
let request = Alamofire.request("https://httpbin.org/ip")
print(request)
// GET https://httpbin.org/ip (200)
CustomDebugStringConvertible
let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
debugPrint(request)
Outputs:
$ curl -i \
-H "User-Agent: Alamofire/4.0.0" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \
"https://httpbin.org/get?foo=bar"
Advanced Usage
Alamofire is built on URLSession
and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack.
Recommended Reading
- URL Loading System Programming Guide
- URLSession Class Reference
- URLCache Class Reference
- URLAuthenticationChallenge Class Reference
Session Manager
Top-level convenience methods like Alamofire.request
use a default instance of Alamofire.SessionManager
, which is configured with the default URLSessionConfiguration
.
As such, the following two statements are equivalent:
Alamofire.request("https://httpbin.org/get")
let sessionManager = Alamofire.SessionManager.default
sessionManager.request("https://httpbin.org/get")
Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (httpAdditionalHeaders
) or timeout interval (timeoutIntervalForRequest
).
Creating a Session Manager with Default Configuration
let configuration = URLSessionConfiguration.default
let sessionManager = Alamofire.SessionManager(configuration: configuration)
Creating a Session Manager with Background Configuration
let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")
let sessionManager = Alamofire.SessionManager(configuration: configuration)
Creating a Session Manager with Ephemeral Configuration
let configuration = URLSessionConfiguration.ephemeral
let sessionManager = Alamofire.SessionManager(configuration: configuration)
Modifying the Session Configuration
var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = defaultHeaders
let sessionManager = Alamofire.SessionManager(configuration: configuration)
This is not recommended for
Authorization
orContent-Type
headers. Instead, use theheaders
parameter in the top-levelAlamofire.request
APIs,URLRequestConvertible
andParameterEncoding
, respectively.
Session Delegate
By default, an Alamofire SessionManager
instance creates a SessionDelegate
object to handle all the various types of delegate callbacks that are generated by the underlying URLSession
. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons.
Override Closures
The first way to customize the SessionDelegate
behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching SessionDelegate
API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available:
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
The following is a short example of how to use the taskWillPerformHTTPRedirection
to avoid following redirects to any apple.com
domains.
let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default)
let delegate: Alamofire.SessionDelegate = sessionManager.delegate
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
var finalRequest = request
if
let originalRequest = task.originalRequest,
let urlString = originalRequest.url?.urlString,
urlString.contains("apple.com")
{
finalRequest = originalRequest
}
return finalRequest
}
Subclassing
Another way to override the default implementation of the SessionDelegate
is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here’s a quick example of subclassing the SessionDelegate
and logging a message when a redirect occurs.
class LoggingSessionDelegate: SessionDelegate {
override func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
print("URLSession will perform HTTP redirection to request: \(request)")
super.urlSession(
session,
task: task,
willPerformHTTPRedirection: response,
newRequest: request,
completionHandler: completionHandler
)
}
}
Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort.
It is important to keep in mind that the
subdelegates
are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks.
Request
The result of a request
, download
, upload
or stream
methods are a DataRequest
, DownloadRequest
, UploadRequest
and StreamRequest
which all inherit from Request
. All Request
instances are always created by an owning session manager, and never initialized directly.
Each subclass has specialized methods such as authenticate
, validate
, responseJSON
and uploadProgress
that each return the caller instance in order to facilitate method chaining.
Requests can be suspended, resumed and cancelled:
suspend()
: Suspends the underlying task and dispatch queue.resume()
: Resumes the underlying task and dispatch queue. If the owning manager does not havestartRequestsImmediately
set totrue
, the request must callresume()
in order to start.cancel()
: Cancels the underlying task, producing an error that is passed to any registered response handlers.
Routing Requests
As apps grow in size, it’s important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire URLConvertible
and URLRequestConvertible
protocols along with the Router
design pattern are here to help.
URLConvertible
Types adopting the URLConvertible
protocol can be used to construct URLs, which are then used to construct URL requests internally. String
, URL
, and URLComponents
conform to URLConvertible
by default, allowing any of them to be passed as url
parameters to the request
, upload
, and download
methods:
let urlString = "https://httpbin.org/post"
Alamofire.request(urlString, method: .post)
let url = URL(string: urlString)!
Alamofire.request(url, method: .post)
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)!
Alamofire.request(urlComponents, method: .post)
Applications interacting with web applications in a significant manner are encouraged to have custom types conform to URLConvertible
as a convenient way to map domain-specific models to server resources.
Type-Safe Routing
extension User: URLConvertible {
static let baseURLString = "https://example.com"
func asURL() throws -> URL {
let urlString = User.baseURLString + "/users/\(username)/"
return try urlString.asURL()
}
}
let user = User(username: "mattt")
Alamofire.request(user) // https://example.com/users/mattt
URLRequestConvertible
Types adopting the URLRequestConvertible
protocol can be used to construct URL requests. URLRequest
conforms to URLRequestConvertible
by default, allowing it to be passed into request
, upload
, and download
methods directly (this is the recommended way to specify custom HTTP body for individual requests):
let url = URL(string: "https://httpbin.org/post")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let parameters = ["foo": "bar"]
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
// No-op
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest)
Applications interacting with web applications in a significant manner are encouraged to have custom types conform to URLRequestConvertible
as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state.
API Parameter Abstraction
enum Router: URLRequestConvertible {
case search(query: String, page: Int)
static let baseURLString = "https://example.com"
static let perPage = 50
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let result: (path: String, parameters: Parameters) = {
switch self {
case let .search(query, page) where page > 0:
return ("/search", ["q": query, "offset": Router.perPage * page])
case let .search(query, _):
return ("/search", ["q": query])
}
}()
let url = try Router.baseURLString.asURL()
let urlRequest = URLRequest(url: url.appendingPathComponent(result.path))
return try URLEncoding.default.encode(urlRequest, with: result.parameters)
}
}
Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50
CRUD & Authorization
import Alamofire
enum Router: URLRequestConvertible {
case createUser(parameters: Parameters)
case readUser(username: String)
case updateUser(username: String, parameters: Parameters)
case destroyUser(username: String)
static let baseURLString = "https://example.com"
var method: HTTPMethod {
switch self {
case .createUser:
return .post
case .readUser:
return .get
case .updateUser:
return .put
case .destroyUser:
return .delete
}
}
var path: String {
switch self {
case .createUser:
return "/users"
case .readUser(let username):
return "/users/\(username)"
case .updateUser(let username, _):
return "/users/\(username)"
case .destroyUser(let username):
return "/users/\(username)"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try Router.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .createUser(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
case .updateUser(_, let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
default:
break
}
return urlRequest
}
}
Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt
Adapting and Retrying Requests
Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered.
The RequestAdapter
and RequestRetrier
protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services.
RequestAdapter
The RequestAdapter
protocol allows each Request
made on a SessionManager
to be inspected and adapted before being created. One very specific way to use an adapter is to append an Authorization
header to requests behind a certain type of authentication.
class AccessTokenAdapter: RequestAdapter {
private let accessToken: String
init(accessToken: String) {
self.accessToken = accessToken
}
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") {
urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
}
return urlRequest
}
}
let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")
sessionManager.request("https://httpbin.org/get")
RequestRetrier
The RequestRetrier
protocol allows a Request
that encountered an Error
while being executed to be retried. When using both the RequestAdapter
and RequestRetrier
protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here’s an example of how you could implement a refresh flow for OAuth2 access tokens.
DISCLAIMER: This is NOT a global
OAuth2
solution. It is merely an example demonstrating how one could use theRequestAdapter
in conjunction with theRequestRetrier
to create a thread-safe refresh system.To reiterate, do NOT copy this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type.
class OAuth2Handler: RequestAdapter, RequestRetrier {
private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void
private let sessionManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
private let lock = NSLock()
private var clientID: String
private var baseURLString: String
private var accessToken: String
private var refreshToken: String
private var isRefreshing = false
private var requestsToRetry: [RequestRetryCompletion] = []
// MARK: - Initialization
public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) {
self.clientID = clientID
self.baseURLString = baseURLString
self.accessToken = accessToken
self.refreshToken = refreshToken
}
// MARK: - RequestAdapter
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) {
var urlRequest = urlRequest
urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
return urlRequest
}
return urlRequest
}
// MARK: - RequestRetrier
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
lock.lock() ; defer { lock.unlock() }
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
requestsToRetry.append(completion)
if !isRefreshing {
refreshTokens { [weak self] succeeded, accessToken, refreshToken in
guard let strongSelf = self else { return }
strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() }
if let accessToken = accessToken, let refreshToken = refreshToken {
strongSelf.accessToken = accessToken
strongSelf.refreshToken = refreshToken
}
strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) }
strongSelf.requestsToRetry.removeAll()
}
}
} else {
completion(false, 0.0)
}
}
// MARK: - Private - Refresh Tokens
private func refreshTokens(completion: @escaping RefreshCompletion) {
guard !isRefreshing else { return }
isRefreshing = true
let urlString = "\(baseURLString)/oauth2/token"
let parameters: [String: Any] = [
"access_token": accessToken,
"refresh_token": refreshToken,
"client_id": clientID,
"grant_type": "refresh_token"
]
sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { [weak self] response in
guard let strongSelf = self else { return }
if
let json = response.result.value as? [String: Any],
let accessToken = json["access_token"] as? String,
let refreshToken = json["refresh_token"] as? String
{
completion(true, accessToken, refreshToken)
} else {
completion(false, nil, nil)
}
strongSelf.isRefreshing = false
}
}
}
let baseURLString = "https://some.domain-behind-oauth2.com"
let oauthHandler = OAuth2Handler(
clientID: "12345678",
baseURLString: baseURLString,
accessToken: "abcd1234",
refreshToken: "ef56789a"
)
let sessionManager = SessionManager()
sessionManager.adapter = oauthHandler
sessionManager.retrier = oauthHandler
let urlString = "\(baseURLString)/some/endpoint"
sessionManager.request(urlString).validate().responseJSON { response in
debugPrint(response)
}
Once the OAuth2Handler
is applied as both the adapter
and retrier
for the SessionManager
, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed.
If you needed them to execute in the same order they were created, you could sort them by their task identifiers.
The example above only checks for a 401
response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the realm
and most likely the www-authenticate
header response although it depends on the OAuth2 implementation.
Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a default
and ephemeral
session configuration for the same set of web services. The example above allows the same oauthHandler
instance to be shared across multiple session managers to manage the single refresh flow.
Custom Response Serialization
Alamofire provides built-in response serialization for data, strings, JSON, and property lists:
Alamofire.request(...).responseData { (resp: DataResponse<Data>) in ... }
Alamofire.request(...).responseString { (resp: DataResponse<String>) in ... }
Alamofire.request(...).responseJSON { (resp: DataResponse<Any>) in ... }
Alamofire.request(...).responsePropertyList { resp: DataResponse<Any>) in ... }
Those responses wrap deserialized values (Data, String, Any) or errors (network, validation errors), as well as meta-data (URL request, HTTP headers, status code, metrics, …).
You have several ways to customize all of those response elements:
- Response Mapping
- Handling Errors
- Creating a Custom Response Serializer
- Generic Response Object Serialization
Response Mapping
Response mapping is the simplest way to produce customized responses. It transforms the value of a response, while preserving eventual errors and meta-data. For example, you can turn a json response DataResponse<Any>
into a response that holds an application model, such as DataResponse<User>
. You perform response mapping with the DataResponse.map
method:
Alamofire.request("https://example.com/users/mattt").responseJSON { (response: DataResponse<Any>) in
let userResponse = response.map { json in
// We assume an existing User(json: Any) initializer
return User(json: json)
}
// Process userResponse, of type DataResponse<User>:
if let user = userResponse.value {
print("User: { username: \(user.username), name: \(user.name) }")
}
}
When the transformation may throw an error, use flatMap
instead:
Alamofire.request("https://example.com/users/mattt").responseJSON { response in
let userResponse = response.flatMap { json in
try User(json: json)
}
}
Response mapping is a good fit for your custom completion handlers:
@discardableResult
func loadUser(completionHandler: @escaping (DataResponse<User>) -> Void) -> Alamofire.DataRequest {
return Alamofire.request("https://example.com/users/mattt").responseJSON { response in
let userResponse = response.flatMap { json in
try User(json: json)
}
completionHandler(userResponse)
}
}
loadUser { response in
if let user = response.value {
print("User: { username: \(user.username), name: \(user.name) }")
}
}
When the map/flatMap closure may process a big amount of data, make sure you execute it outside of the main thread:
@discardableResult
func loadUser(completionHandler: @escaping (DataResponse<User>) -> Void) -> Alamofire.DataRequest {
let utilityQueue = DispatchQueue.global(qos: .utility)
return Alamofire.request("https://example.com/users/mattt").responseJSON(queue: utilityQueue) { response in
let userResponse = response.flatMap { json in
try User(json: json)
}
DispatchQueue.main.async {
completionHandler(userResponse)
}
}
}
map
and flatMap
are also available for download responses.
Handling Errors
Before implementing custom response serializers or object serialization methods, it’s important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an Error
type specific to your app.
For example, here’s a simple BackendError
enum which will be used in later examples:
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
Creating a Custom Response Serializer
Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on Alamofire.DataRequest
and / or Alamofire.DownloadRequest
.
For example, here’s how a response handler using Ono might be implemented:
extension DataRequest {
static func xmlResponseSerializer() -> DataResponseSerializer<ONOXMLDocument> {
return DataResponseSerializer { request, response, data, error in
// Pass through any underlying URLSession error to the .network case.
guard error == nil else { return .failure(BackendError.network(error: error!)) }
// Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has
// already been handled.
let result = Request.serializeResponseData(response: response, data: data, error: nil)
guard case let .success(validData) = result else {
return .failure(BackendError.dataSerialization(error: result.error! as! AFError))
}
do {
let xml = try ONOXMLDocument(data: validData)
return .success(xml)
} catch {
return .failure(BackendError.xmlSerialization(error: error))
}
}
}
@discardableResult
func responseXMLDocument(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<ONOXMLDocument>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.xmlResponseSerializer(),
completionHandler: completionHandler
)
}
}
Generic Response Object Serialization
Generics can be used to provide automatic, type-safe response object serialization.
protocol ResponseObjectSerializable {
init?(response: HTTPURLResponse, representation: Any)
}
extension DataRequest {
func responseObject<T: ResponseObjectSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<T>) -> Void)
-> Self
{
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response, let responseObject = T(response: response, representation: jsonObject) else {
return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)"))
}
return .success(responseObject)
}
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
struct User: ResponseObjectSerializable, CustomStringConvertible {
let username: String
let name: String
var description: String {
return "User: { username: \(username), name: \(name) }"
}
init?(response: HTTPURLResponse, representation: Any) {
guard
let username = response.url?.lastPathComponent,
let representation = representation as? [String: Any],
let name = representation["name"] as? String
else { return nil }
self.username = username
self.name = name
}
}
Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse<User>) in
debugPrint(response)
if let user = response.result.value {
print("User: { username: \(user.username), name: \(user.name) }")
}
}
The same approach can also be used to handle endpoints that return a representation of a collection of objects:
protocol ResponseCollectionSerializable {
static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self]
}
extension ResponseCollectionSerializable where Self: ResponseObjectSerializable {
static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] {
var collection: [Self] = []
if let representation = representation as? [[String: Any]] {
for itemRepresentation in representation {
if let item = Self(response: response, representation: itemRepresentation) {
collection.append(item)
}
}
}
return collection
}
}
extension DataRequest {
@discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self
{
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible {
let username: String
let name: String
var description: String {
return "User: { username: \(username), name: \(name) }"
}
init?(response: HTTPURLResponse, representation: Any) {
guard
let username = response.url?.lastPathComponent,
let representation = representation as? [String: Any],
let name = representation["name"] as? String
else { return nil }
self.username = username
self.name = name
}
}
Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in
debugPrint(response)
if let users = response.result.value {
users.forEach { print("- \($0)") }
}
}
Security
Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple’s built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the ServerTrustPolicy
.
ServerTrustPolicy
The ServerTrustPolicy
enumeration evaluates the server trust generally provided by an URLAuthenticationChallenge
when connecting to a server over a secure HTTPS connection.
let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
certificates: ServerTrustPolicy.certificates(),
validateCertificateChain: true,
validateHost: true
)
There are many different cases of server trust evaluation giving you complete control over the validation process:
performDefaultEvaluation
: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge.pinCertificates
: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates.pinPublicKeys
: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys.disableEvaluation
: Disables all evaluation which in turn will always consider any server trust as valid.customEvaluation
: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution.
Server Trust Policy Manager
The ServerTrustPolicyManager
is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy.
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"test.example.com": .pinCertificates(
certificates: ServerTrustPolicy.certificates(),
validateCertificateChain: true,
validateHost: true
),
"insecure.expired-apis.com": .disableEvaluation
]
let sessionManager = SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
Make sure to keep a reference to the new
SessionManager
instance, otherwise your requests will all get cancelled when yoursessionManager
is deallocated.
These server trust policies will result in the following behavior:
test.example.com
will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed:
- Certificate chain MUST be valid.
- Certificate chain MUST include one of the pinned certificates.
- Challenge host MUST match the host in the certificate chain’s leaf certificate.
insecure.expired-apis.com
will never evaluate the certificate chain and will always allow the TLS handshake to succeed.- All other hosts will use the default evaluation provided by Apple.
Subclassing Server Trust Policy Manager
If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the ServerTrustPolicyManager
and override the serverTrustPolicyForHost
method with your own custom implementation.
class CustomServerTrustPolicyManager: ServerTrustPolicyManager {
override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
var policy: ServerTrustPolicy?
// Implement your custom domain matching behavior...
return policy
}
}
Validating the Host
The .performDefaultEvaluation
, .pinCertificates
and .pinPublicKeys
server trust policies all take a validateHost
parameter. Setting the value to true
will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A validateHost
value of false
will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate.
It is recommended that
validateHost
always be set totrue
in production environments.
Validating the Certificate Chain
Pinning certificates and public keys both have the option of validating the certificate chain using the validateCertificateChain
parameter. By setting this value to true
, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of false
will skip the certificate chain validation, but will still perform the byte equality check.
There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server.
It is recommended that
validateCertificateChain
always be set totrue
in production environments.
App Transport Security
With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom ServerTrustPolicyManager
with several ServerTrustPolicy
objects will have no effect. If you continuously see CFNetwork SSLHandshake failed (-9806)
errors, you have probably run into this problem. Apple’s ATS system overrides the entire challenge system unless you configure the ATS settings in your app’s plist to disable enough of it to allow your app to evaluate the server trust.
If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your Info.plist
.
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
<!-- Optional: Specify minimum TLS version -->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
</dict>
</dict>
</dict>
</dict>
Whether you need to set the NSExceptionRequiresForwardSecrecy
to NO
depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to NO
. The NSExceptionAllowsInsecureHTTPLoads
MUST be set to YES
in order to allow the SessionDelegate
to receive challenge callbacks. Once the challenge callbacks are being called, the ServerTrustPolicyManager
will take over the server trust evaluation. You may also need to specify the NSTemporaryExceptionMinimumTLSVersion
if you’re trying to connect to a host that only supports TLS versions less than 1.2
.
It is recommended to always use valid certificates in production environments.
Network Reachability
The NetworkReachabilityManager
listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces.
let manager = NetworkReachabilityManager(host: "www.apple.com")
manager?.listener = { status in
print("Network Status Changed: \(status)")
}
manager?.startListening()
Make sure to remember to retain the
manager
in the above example, or no status changes will be reported.
Also, do not include the scheme in thehost
string or reachability won’t function correctly.
There are some important things to remember when using network reachability to determine what to do next.
- Do NOT use Reachability to determine if a network request should be sent.
- You should ALWAYS send it.
- When Reachability is restored, use the event to retry failed network requests.
- Even though the network requests may still fail, this is a good moment to retry them.
- The network reachability status can be useful for determining why a network request may have failed.
- If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as “request timed out.”
It is recommended to check out WWDC 2012 Session 706, “Networking Best Practices” for more info.