Alamofire是基于Apple提供的 URL加载系统,核心是URLSession和URLSessionTask子类。 早期版本使用Alamofire.request(),5.0版本使用AF命名,AF引用Session.default
一、发起请求
两个发起请求的API
/// 1. 配置请求组成 URLRequest、本篇主要内容(基础用法)open func request<Parameters:Encodable>(_convertible:URLConvertible,method:HTTPMethod=.get,parameters:Parameters?=nil,encoder:ParameterEncoder=URLEncodedFormParameterEncoder.default,headers:HTTPHeaders?=nil,interceptor:RequestInterceptor?=nil)->DataRequest///
2. 直接请求组装好的 URLRequest (高级用法)open func request(_urlRequest:URLRequestConvertible,interceptor:RequestInterceptor?=nil)->DataRequest1)
参数需要遵从Encodable 协议
只要参数遵循Encodable协议,那么最终ParameterEncoder都会把Parameter encode成需要的数据类型
举例:


2)参数编码器:
参数编码器 最终决定了参数在请求中的存在的样式;我们通过参数编码器把参数编码成服务器需要的数据类型。
2.1) JSON参数编码器:JSONParameterEncoder
JSONParameterEncoder 对应的 Content-Type 为 application/json
3中样式:
default
prettyPrinted 好看的格式打印
sortedKeys key 排序
最终都是调用 encode 将参数转为 Data 保存在 httpBody 中
2.2) Form参数编码器:URLEncodedFormParameterEncoder
URLEncodedFormParameterEncoder 对应的 Content-Type 为
application/x-www-form-urlencoded; charset=utf-8
Form参数编码器只有一个默认的编码器default
2.2.1 Destination 决定参数存放的位置。
methodDependent [.get, .head, .delete] 拼接URL ,默认使用此方
式。
queryString 拼接URL。
httpBody。
2.2.2 URLEncodedFormEncoder 决定了参数中不同类型的key,value
编码方式。



3)HTTP Headers 请求头设置
提供3种初始化方式



4)响应处理
Alamofire 提供了4种 Response序列化工具
DataResponseSerializer 解析为Data

StringResponseSerializer 解析为String

JSONResponseSerializer 解析为JSON

DecodableResponseSerializer 解析为指定类型<T: Decodable>

DataResponseSerializerProtocol 使用自定义解析 Serializer:




二、下载文件
1)下载Data

2)下载到指定目录

3)下载进度

4)恢复下载

三、上传文件
1)上传 Data


2)上传文件


3)上传 Multipart Data

4)上传进度

注意其中的HTTPBinResponse 为自定义的类型
网友评论