Alamofire
Alamofire 是一个用 Swift 编写的 HTTP 网络库,基于 Foundation URL 加载系统,提供了优雅的 API 设计,让网络请求变得更加简单高效。
功能特性
- 优雅的链式 API:简洁直观的请求构建方式
-
- 全面的 HTTP 方法支持:GET、POST、PUT、DELETE 等
-
- 参数编码:支持 URL 编码、JSON 编码等多种参数编码方式
-
- 响应序列化:内置 JSON、字符串、数据等多种响应解析方式
-
- 请求/响应拦截:支持请求适配器和重试机制
-
- 身份验证:支持基本认证、OAuth 等
-
- 文件上传/下载:支持进度跟踪和断点续传
-
- SSL 证书验证:增强网络安全性
-
- 全面的平台支持:iOS、macOS、watchOS 和 tvOS
安装指南
Swift Package Manager
在 Package.swift 中添加依赖:
dependencies: [
.package(url: https://github.com/Alamofire/Alamofire.git, from: 5.0.0)
]
CocoaPods
在 Podfile 中添加:
pod 'Alamofire', '~> 5.0'
Carthage
在 Cartfile 中添加:
github Alamofire/Alamofire ~> 5.0
使用说明
基本请求
import Alamofire
AF.request(https://httpbin.org/get).response { response in
debugPrint(response)
}
POST 请求
let parameters = [username: user, password: 123456]
AF.request(https://httpbin.org/post,
method: .post,
parameters: parameters).responseJSON { response in
switch response.result {
case .success(let value):
print(Response: \(value))
case .failure(let error):
print(Error: \(error))
}
}
下载文件
AF.download(https://httpbin.org/image/png).responseData { response in
if let data = response.value {
let image = UIImage(data: data)
}
}
上传文件
let fileURL = Bundle.main.url(forResource: video, withExtension: mov)
AF.upload(fileURL, to: https://httpbin.org/post).uploadProgress { progress in
print(Upload Progress: \(progress.fractionCompleted))
}.responseJSON { response in
debugPrint(response)
}