Alamofire是Swift开发者最熟悉也是最常使用的网络框架,源码中应用了Swift这门年轻语言的很多新特性,包括了很多泛型、枚举、协议及扩展的高级使用。
DataRequest
先来看一个简单的Alamofire网络请求:
request(requestUrl, method: .get , parameters: params).responseString{ (responseStr) in
switch responseStr.result{
case .success(let value):
//拿到请求成功的数据做处理
case .failure(let error):
//失败处理
}
}
request(requestUrl, method: .get , parameters: params)方法返回的是一个DataRequest类型的对象,继承自Request类,也就是Alamofire封装的请求类,Request封装了NSURLSessionTask以及Task的基本的代理方法。接着利用DataRequest的responseString方法将请求回来的二进制数据序列化成字符串类型,而回调回来的responseStr字符串是通过responseStr.result中的枚举值.success来获得的,我们接下来就来简单分析一下这么一个简单的网络封装的工具方法在源码中是怎么实现的。
(注意:此处因为是普通的get、post请求,所以返回的是DataRequest类,如果是下载或者上传,则需要调用download或upload方法,返回的则是DownloadRequest或UploadRequest类)。
先看request方法的封装实现:
// MARK: - Data Request
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest //返回类型
{
var originalRequest: URLRequest?
do {
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
return request(encodedURLRequest) //调用下方的方法
} catch {
return request(originalRequest, failedWith: error)
}
}
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
var originalRequest: URLRequest?
do {
originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(originalRequest, failedWith: error)
}
}
下面来看看关键的网络请求完成并且序列化数据的封装方法,也就是上面代码中的responseString是如何实现的,DataRequest的扩展中提供了五类方法,用来将response序列化成不同类型的数据,以满足实际的需要,包括Default、Data、String、JSON对象以及Plist类型,而所有这些扩展都被Alamofire放在了ResponseSerialization.swift这个文件里。
ResponseSerialization
我们以其中的responseString为例,先看源码:
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
//response方法,第二个参数要遵循DataResponseSerializerProtocol
public func response<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
-> Self
返回一个response方法的实现,completionHandler是最终网络返回的闭包回调,继续传进去给response方法。先看第二个参数 responseSerializer,要遵循DataResponseSerializerProtocol这个协议,此处传入 DataRequest.stringResponseSerializer(encoding: encoding),进入这个方法:
extension DataRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
}
}
就是 通过调用这个方法 返回一个 DataResponseSerializer结构体。
DataResponse
再来看看DataResponseSerializer,他遵循 DataResponseSerializerProtocol,在初始化init方法中:
public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol {
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
给自己的serializeResponse闭包赋值(此处闭包的返回值 在不同的response序列化数据类型中 根据情况 使用,并返回不同的Result),而上面的这个方法:
//返回值正是Result<String>
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
//实现方法
public static func serializeResponseString(
encoding: String.Encoding?,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<String>
该返回值Result<String>就是网络请求成功后处理完的返回值,也是我们最终需要得到的结果,那上面这个DataResponseSerializer的闭包又是在哪返回的Result呢,再回到这个函数:
return response(
queue: queue,
responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
就是在response方法中处理的,来看具体实现:
public func response<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
-> Self
{
//确保在网络请求成功后再处理后续操作
delegate.queue.addOperation {
//调用responseSerializer的闭包,进行处理获得result结果
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
//初始化一个dataResponse,并回调出去
var dataResponse = DataResponse<T.SerializedObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
//回调出去
(queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }
}
return self
}
上面的delegate.queue.addOperation {} 保证了这个operation会在网络请求成功后再执行,然后通过调用let result = responseSerializer.serializeResponse(...),闭包属性responseSerializer的返回值为Result,最后将dataResponse通过dcompletionHandler(dataResponse) 回调出去,而dataResponse
public struct DataResponse<Value> {
public init(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
result: Result<Value>,
timeline: Timeline = Timeline())
{
self.request = request
self.response = response
self.data = data
self.result = result //最终我们需要的序列化好的数据Result<Value>
self.timeline = timeline
}
}
而这个Result<Value>就是个枚举,利用了泛型,例如网络请求返回的不同类型的结果(Data、String),结构如下:
public enum Result<Value> {
case success(Value)
case failure(Error)
}
以上就是Alamofire中一个简单网络请求封装的过程,通过源码解析也一定程度上将Swift的网络请求知识点再巩固了一遍。