本文主要是练习Moya的熟练使用
简单的网络请求
1.创建baseTargetType
主要是添加了baseUrl省去了每次创建接口都要写的步骤
extension TargetType {
public var baseURL: URL {
return URL(string: "https://api.github.com/")!
}
}
2.创建接口
enum Github {
case repositories(q: String,sort: String)
}
3.拓展接口
extension Github: TargetType {
var path: String {
switch self {
case .repositories:
return "search/repositories"
}
}
var method: Moya.Method {
switch self {
case .repositories:
return .get
}
}
var parameters: [String: Any]? {
switch self {
case .repositories(let q,let sort):
return ["q": q,"sort": sort]
}
}
var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
var task: Task {
return .request
}
var sampleData: Data {
switch self {
case .repositories:
return "".utf8Encoded
}
}
}
extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
var utf8Encoded: Data {
return self.data(using: .utf8)!
}
}
参数说明
- path 就是API的地址了(该demo完整的URL是https://api.github.com/search/repositories?q=javascript&sort=stars)
- method 请求的方式:get/post
- parameters API参数,以Map形式提交
- parameterEncoding 参数的格式
- task 该条请API求的方式,request、upload、download
- sampleData 这个是做单元测试模拟的数据,必须要实现,只在单元测试文件中有作用
4.创建一个Provider
let GithubRxProvicer = RxMoyaProvider<Github>(plugins: [NetworkLoggerPlugin(verbose: true,responseDataFormatter: JSONResponseDataFormatter),networkActivityPlugin])
private func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON,options: .prettyPrinted)
return prettyData
} catch {
return data //fallback to original data if it cant be serialized
}
}
let networkActivityPlugin = NetworkActivityPlugin { (change) -> () in
switch(change) {
case .ended:
UIApplication.shared.isNetworkActivityIndicatorVisible = false
case .began:
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
补充
Moya在初始化Provider的时候可以传入一些插件,Moya库中默认有4个插件。
- AccessTokenPlugin 管理AccessToken的插件
- CredentialsPlugin 管理认证的插件
- NetworkActivityPlugin 管理网络状态的插件
- NetworkLoggerPlugin 管理网络log的插件
且,自己也可以创建plugin;比如:
class RequestAlertPlugin: PluginType { private let viewController: UIViewController init(viewController: UIViewController) { self.viewController = viewController } func willSend(request: RequestType,target: TargetType) { //do your things } func didReceive(result: Result<Response,MoyaError>,target: TargetType) { guard case Result.failure(_) = result else { return }//只监听失败 // do your things } }
5.使用
GithubRxProvicer.request(.repositories(q: "javascript",sort: "stars"))
.mapResponseToObject(type: Repositorie.self)
.subscribe { event in
switch event {
case .next(let data):
print(".next")
case .error(let error):
print(error)
case .completed:
print(".completed")
}
}
.disposed(by: disposeBag)
补充
Moya也为我们提供了很多Observable的扩展,让我们能更轻松的处理MoyaResponse,常用的如下:
- filter(statusCodes:) 过滤response状态码
- filterSuccessfulStatusCodes() 过滤状态码为请求成功的
- mapJSON() 将请求response转化为JSON格式
- mapString() 将请求response转化为String格式