Swift moya - 学习笔记
发布时间:2020-12-14 06:07:39 所属栏目:百科 来源:网络整理
导读:本文主要是练习Moya的熟练使用 简单的网络请求 1.创建baseTargetType 主要是添加了baseUrl省去了每次创建接口都要写的步骤 extension TargetType { public var baseURL: URL { return URL( string : "https://api.github.com/" )! }} 2.创建接口 enum Github
本文主要是练习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)!
}
}
参数说明
4.创建一个Providerlet 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个插件。
且,自己也可以创建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,常用的如下:
更多使用参考可以参考这篇文章,里面很详细的介绍了moya的各种用法 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |