天天看点

iOS - Alamofire 网络请求前言1、Alamofire2、Alamofire 的添加3、Alamofire 的设置4、Alamofire HTTP 认证5、Alamofire HTTP 响应状态信息识别6、Alamofire Timeline7、Alamofire 调试打印8、Alamofire 网络连接状态检查9、Alamofire 异步 GET 数据请求10、Alamofire 文件下载11、Alamofire 异步 POST 数据请求12、Alamofire 文件上传

Alamofire 是 Swift 语言的 HTTP 网络开发工具包,相当于 Swift 实现 AFNetworking 版本。当然,AFNetworking 非常稳定,在 Mac OSX 与 iOS 中也能像其他 Objective-C 代码一样用 Swift 编写。不过 Alamofire 更适合 Swift 语言风格习惯(Alamofire 与 AFNetworking 可以共存一个项目中,互不影响)。Alamofire 取名来源于 Alamo Fire flower。

Alamofire 的核心主要是试图简化 iOS 中 HTTP 网络连接,它通过使用 NSURLSession 以及 Foundation URL Loading System 来创建一个 Swift 本地的网络访问接口,从而实现令人难以置信效率的任务。

Alamofire 功能:

Chainable Request / Response methods

URL / JSON / plist Parameter Encoding

Upload File / Data / Stream

Download using Request or Resume data

Authentication with NSURLCredential

Progress Closure & NSProgress

cURL Debug Output

Alamofire 系统需求:

Alamofire Version

Minimum iOS Target

Target Notes

3.4.x

iOS 8.0+

Xcode 7.3+ is required.

3.1.4 -> 3.3.1

Xcode 7.2+ is required.

3.1.0 -> 3.1.3

Xcode 7.1+ is required.

2.0.0 -> 3.0.1

Xcode 7.0+ is required.

1.3.0 -> 1.3.1

iOS 7.0+

Xcode 6.4 is required.

1.2.1 -> 1.2.3

Xcode 6.3 is required.

1.1.0 -> 1.2.0

Xcode 6.1 is required.

1.0.0 -> 1.0.1

Xcode 6.0 is required. For Xcode 6.1, use the xcode-6.1 branch.

Alamofire 有许多让程序猿信服去使用它的理由。在 iOS 开发中,使用 NURLSession 是 HTTP 网络的未来趋势, 相比 NSURLConnection 来说,它的功能更加丰富:

后台上传和下载

暂停以及重新开始网络操作的能力

可配置的容器(Container)

子类和私有存储

改进的认证处理

对每个基础连接进行身份验证

多种代理模式 -- NSURLConnection 拥有异步代码块的基本方法, 但是不能用它们的代理,NSURLSession 具有一种混合型的方法。

对 AFNetworking 能做而 Alamofire 不能做的有以下几点:

UIKit 扩展

TLS 验证

NSOperation/NSURLConnection/AFURLConnectionOperation 调用

多重 HTTP 网络请求构架

Alamofire 使用 ARC

Swift

请求超时时间设置

HTTP 方法(Medthods)

请求参数编码方式设置

请求头设置

请求数据响应格式设置

Request 请求创建方式

请求任务创建方式

请求任务设置

文件下载设置

文件上传设置

支持以下几种认证:

HTTP Basic

HTTP Digest

Kerberos

NTLM

手动识别

自动识别

支持的类型:

Request

Resume Data

默认支持后台方式下载

指定文件路径方式

使用默认提供的下载路径方式

断点续传下载方式

Alamofire 方式

Manager 方式

支持的类型:

File

Data

Stream

MultipartFormData

Data 形式上传

MultipartFormData 形式上传