Moya 简介
Moya
是一套基于Alamofire
的网络抽象层框架。
个人认为Alamofire
是基于URLSession
上,如何更方便的调用请求,而Moya
则是基于Alamofire
上,通过抽象 URLs 和 parameter等等,更好的管理API。
[图片上传失败...(image-b699d0-1569852473172)]
<figcaption></figcaption>
基本模板
Moya
在对于API的封装是基于enum
,通过对于枚举不同端点的不同用法,生成请求。
enum GitHub {
case zen
case userProfile(String)
}
extension GitHub: TargetType {
var baseURL: URL { return URL(string: "https://api.github.com")! }
var path: String {
switch self {
case .zen:
return "/zen"
case .userProfile(let name):
return "/users/\(name)"
}
}
var method: Moya.Method {
return .get
}
var task: Task {
return .requestPlain
}
var sampleData: Data {
switch self {
case .zen:
return "Half measures are as bad as nothing at all.".data(using: String.Encoding.utf8)!
case .userProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".data(using: String.Encoding.utf8)!
}
}
var validationType: ValidationType {
return .successAndRedirectCodes
}
var headers: [String: String]? {
return nil
}
}
复制代码
通过枚举继承TargetType
,添加细节实现。
var provider = MoyaProvider<GitHub>()
provider.request(target) { response in
if case .failure(let error) = response {
receivedError = error
}
}
复制代码
最后生成根据TargetType生成provider进行请求。
到此就是Moya
的基本实现。因为过于基本,不再赘述。
Codable
Codable
协议是苹果提供解析数据的协议,在不使用第三方库,如ObjectMapper
, SwiftyJson
的情况下,将服务器返回的JSON
数据转为model。
下面是一个简单的Codable
示例:
struct Demo: Codable {
var name: String
var age: Int
}
func decode() {
let jsonString = "{\"name\":\"zhangsan\", \"age\":15}" // 模拟JSON数据
let decoder = JSONDecoder()
let data = jsonString.data(using: .utf8)!
let model = try! decoder.decode(Demo.self, from: data)
print(model) // Demo(name: "zhangsan", age: 15)
}
复制代码
在Moya
的Response
中已经封装好了对应的处理
DemoProvider.provider.request(.zen) { (result) in
switch result {
case .success(let response):
if let model = try? response.map(Demo.self) {
success(model)
}
case .failure(let error):
break
}
}
复制代码
如果数据是在JSON的好几个层级中,也可以通过设定keypath获取:
{
data: {
name: "test",
age: 15
}
}
try? response.map(Demo.self, atKeyPath: "data")
复制代码
要注意的是这里函数还有一个参数叫做failsOnEmptyData
,默认设定为true
,如果返回的数据为空,会判定会解析失败。
EndPoint
EndPoint是Moya的半个内部数据结构,由所用的TargetType生成,它最终被用来生成网络请求。 每个EndPoint 都存储了下面的数据:
/// A string representation of the URL for the request.
public let url: String
/// A closure responsible for returning an `EndpointSampleResponse`. (单元测试)
public let sampleResponseClosure: SampleResponseClosure
/// The HTTP method for the request.
public let method: Moya.Method
/// The `Task` for the request.
public let task: Task
/// The HTTP header fields for the request.
public let httpHeaderFields: [String: String]?
复制代码
在Provider生成时,可以传入endpointClosure,自定义TargetType到Endpoint的方式。
默认的实现方式:
final class func defaultEndpointMapping(for target: Target) -> Endpoint {
return Endpoint(
url: URL(target: target).absoluteString,
sampleResponseClosure: { .networkResponse(200, target.sampleData) },
method: target.method,
task: target.task,
httpHeaderFields: target.headers
)
}
复制代码
在这里可以重新定义Endpoint的生成方式, 比如:
// 将所有生成Endpoint改为get方式请求
let endpointClosure = { (target: MyTarget) -> Endpoint in
let url = URL(target: target).absoluteString
return Endpoint(url: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: .get, task: target.task)
}
复制代码
或者对已经生成的Endpoint修改:
let endpointClosure = { (target: MyTarget) -> Endpoint in
let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
return defaultEndpoint.adding(newHTTPHeaderFields: ["APP_NAME": "MY_AWESOME_APP"])
}
复制代码
注意:如果直接对已经初始化的Endpoint修改,只能修改task以及添加header。
Request
在生成Endpoint之后,会从Endpoint再转为URLRequst进行使用。
Moya的默认实现:
RequestResultClosure = (Result<URLRequest, MoyaError>) -> Void
final class func defaultRequestMapping(for endpoint: Endpoint, closure: RequestResultClosure) {
do {
let urlRequest = try endpoint.urlRequest()
closure(.success(urlRequest))
} catch MoyaError.requestMapping(let url) {
closure(.failure(MoyaError.requestMapping(url)))
} catch MoyaError.parameterEncoding(let error) {
closure(.failure(MoyaError.parameterEncoding(error)))
} catch {
closure(.failure(MoyaError.underlying(error, nil)))
}
}
public func urlRequest() throws -> URLRequest {
guard let requestURL = Foundation.URL(string: url) else {
throw MoyaError.requestMapping(url)
}
var request = URLRequest(url: requestURL)
request.httpMethod = method.rawValue
request.allHTTPHeaderFields = httpHeaderFields
switch task {
case .requestPlain, .uploadFile, .uploadMultipart, .downloadDestination:
return request
case .requestData(let data):
request.httpBody = data
return request
......
复制代码
因为内部已经实现如何生成Request,大多情况不需要修改urlRequest
,而是重新定义requestClosure, 对已经生成好的request进行修改,下面是直接修改request的缓存策略,以及错误处理:
let requestClosure = { (endpoint: Endpoint, done: MoyaProvider.RequestResultClosure) in
do {
var request = try endpoint.urlRequest()
request.cachePolicy = .reloadIgnoringCacheData
done(.success(request))
} catch {
done(.failure(MoyaError.underlying(error)))
}
}
复制代码
stubClosure
stubClosure实现:
/// Do not stub.
final class func neverStub(_: Target) -> Moya.StubBehavior {
return .never
}
/// Return a response immediately.
final class func immediatelyStub(_: Target) -> Moya.StubBehavior {
return .immediate
}
/// Return a response after a delay.
final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior {
return { _ in return .delayed(seconds: seconds) }
}
复制代码
Moya的默认实现是neverStub,当使用immediatelyStub或者是delayedStub,请求网络时就不会走真实的数据,而是返回Target中SimpleData的数据,一般用于测试API返回数据的处理。
delayedStub相对于immediatelyStub指定了延迟时长,单位是秒。
callbackQueue
可以指定网络请求返回之后的callback线程。默认所有的请求将会被Alamofire放入background线程中, callbac将会在主线程中调用。
Manager
public typealias Manager = Alamofire.SessionManager
final class func defaultAlamofireManager() -> Manager {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders
let manager = Manager(configuration: configuration)
manager.startRequestsImmediately = false
return manager
}
复制代码
Moya中使用的Manager其实就是Alamofire的Manager。
可以设定Timeout,缓存策略等等
let manager: SessionManager = {
let configuration = defaultURLSessionConfiguration
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.timeoutIntervalForRequest = 20
let trustPolicyManager = ServerTrustPolicyManager(policies:
[
"www.baidu.com": ServerTrustPolicy.disableEvaluation
]
)
let manager = SessionManager(configuration: configuration, serverTrustPolicyManager: trustPolicyManager)
return manager
}()
复制代码
Plugins
plugins
是遵守了PluginType
的插件,一个provider可以方多个Plugin。
PluginType:
public protocol PluginType {
/// 在发送request之前,还有机会对request修改
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest
/// 发送之前调用
func willSend(_ request: RequestType, target: TargetType)
/// 接受Response之后,在触发callback之前
func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType)
/// 在调用Callback之前,还能修改result
func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError>
}
public extension PluginType {
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { return request }
func willSend(_ request: RequestType, target: TargetType) { }
func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) { }
func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> { return result }
}
复制代码
在Plugin中可以做很多事情
- 记录网络请求
- 处理隐藏或者显示网络activity progress
- 对request进行更多的处理
比如:
struct TestPlugin: PluginType {
// 对request进行更多的处理
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
var request = request
if target is GitHub {
request.timeoutInterval = 5
}
return request
}
// 记录网络请求
func willSend(_ request: RequestType, target: TargetType) {
print("start")
print(request.request?.url ?? "")
}
// 记录网络请求
func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
print("end")
switch result {
case .success(let response):
print("end success")
print(response.request?.url ?? "")
case .failure(let error):
print("end failure")
print(error)
}
}
// 对返回的result进行修改
func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
if case let .failure(error) = result {
return .failure(MoyaError.underlying(error, nil))
}
return result
}
}
复制代码
Moya也对Logger,activity等提供了默认实现的Plugin,更多细节就不详细说明了。
trackInflights
源码看了半天还是看不明白,希望懂的朋友能告诉我是怎么用的。
MultiTarget
一般场景下,是一个targetType对应一个Provider
let githubProvider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub, trackInflights: true)
let demoProvider = MoyaProvider<Demo>(stubClosure: MoyaProvider.immediatelyStub, trackInflights: true)
复制代码
但是如果像让这个Provider更通用,可以写为:
let commonProvider = MoyaProvider<MultiTarget>()
复制代码
调用的时候指定TargetType即可:
commonProvider.request(MultiTarget(GitHub.zen)) { result in
...
}
复制代码
流程
补一张网上找到的流程图