一个target可以放多个接口,并且每个接口都可以单独指定url和请求类型,和参数类型.利用的枚举类型
下面代码展示target的用法.先定义一个 enum类型,然后遵守moya的 TargetType协议.
import UIKit
import Moya
import SwiftyJSON
import RxSwift
import RxCocoa
import HandyJSON
public enum JiaZhang :TargetType{
case login([String:String]) //登录
case circle([String:String]) //朋友圈
case logout([String:String]) //退出
public var baseURL: URL {
URL(string: "https://kindergarten.wozhijiao.cn:5057//kindergartenapi/")!
}
public var path: String {
switch self{
case .login:
return "security/oauth/token"
case .circle:
return "circle/circle/queryCircle"
case .logout:
return "base/user/logout"
default:
return ""
}
}
public var method: Moya.Method {
return .post
}
public var sampleData: Data {
switch self{
case .login(let param):
return "登录参数是:\(param)".data(using: .utf8)!
default:
return "没有对应类型".data(using: .utf8)!
}
}
/*
requestParameters设置请求参数,和请求返回的编码格式
URLEncoding.default 相当于 AFNetworking的
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFHTTPRequestSerializer()
JSONEncoding.default相当于 AFNetworking的
manager.requestSerializer = AFJSONRequestSerializer()
*/
public var task: Task {
switch self{
case .login(let params):
return .requestParameters(parameters: params, encoding: URLEncoding.default)//encoding代表接收的请求用什么编码
case .circle(let params):
return .requestParameters(parameters: params, encoding: JSONEncoding.default)
case .logout(let params):
return .requestParameters(parameters: params, encoding: JSONEncoding.default)
default:
return .requestPlain
}
}
public var headers: [String : String]? {
switch self{
case .login:
return nil
/*
case .circle:
let token = UserDefaults.standard.object(forKey: "token") as? String ?? ""
header["Authorization"] = "Bearer " + token
print("header=",header)
return header
case .logout:
let token = UserDefaults.standard.object(forKey: "token") as? String ?? ""
header["Authorization"] = "Bearer " + token
print("header=",header)
return header
*/
default:
return nil
}
}
// 通过statuscode过滤返回内容
public var validationType: ValidationType {
switch self {
case .login:
return .successCodes
default:
return .none
}
}
}
PluginType,这个协议,也是我们要自己写一个子类继承自PluginType.里面有一个prepare方法是每次发送请求之前执行的.在这里可以添加token,注意要新建一个临时变量 var request = request,要不然不能更改里面的值
import UIKit
import Moya
import SwiftyJSON
final class TdwMoyaPlugin: PluginType {
public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
var request = request
request.addValue("token值", forHTTPHeaderField: "token名字")
return request
}
}
import UIKit
import Moya
import SwiftyJSON
public protocol TdwMoyaToken{
var existToken:Bool {
get
}
}
final class TdwMoyaPlugin: PluginType {
//当前的视图控制器
var vc:UIViewController
var existToken = true
//活动状态指示器(菊花进度条)
private var spinner: UIActivityIndicatorView!
//插件初始化的时候传入当前的视图控制器
init(vc:UIViewController) {
self.vc = vc
spinner = UIActivityIndicatorView(style: .gray)//转菊花
spinner.center = self.vc.view.center
}
var tokenVal:String {
get {
guard let myInfo = O2UserDefaults.shared.myInfo else { //加载自己的token
return ""
}
return myInfo.token ?? ""
}
}
var clientVal:String {
get {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
return "iOS \(versionString)"
}
}
public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
var request = request
//加上通用头
request.addValue(clientVal, forHTTPHeaderField: "x-client")
if let authorizable = target as? TdwMoyaToken,authorizable.existToken == false {
return request
}
print("clientVal=",clientVal)
//加上token
let tokenName = O2AuthSDK.shared.tokenName()
request.addValue(tokenVal, forHTTPHeaderField: tokenName)
print("tokenVal=",tokenVal)
print("tokenName=",tokenName)
return request
}
//开始发起请求
func willSend(_ request: RequestType, target: TargetType) {
//请求时在界面中央显示一个活动状态指示器
DispatchQueue.main.async {[weak self] in
self?.vc.view.addSubview(self!.spinner)
self?.spinner.startAnimating()
}
}
//收到请求
func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
//移除界面中央的活动状态指示器
DispatchQueue.main.async {[weak self] in
self?.spinner.removeFromSuperview()
self?.spinner.stopAnimating()
}
//只有请求错误时会继续往下执行
guard case let Result.failure(error) = result else { return }
//弹出并显示错误信息
let message = error.errorDescription ?? "未知错误"
let alertViewController = UIAlertController(title: "请求失败",
message: "\(message)",
preferredStyle: .alert)
alertViewController.addAction(UIAlertAction(title: "确定", style: .default,
handler: nil))
vc.present(alertViewController, animated: true)
}
}
import UIKit
import Moya
import RxSwift
import RxCocoa
import SwiftyJSON
class TdwMoyaProvider<Target>: MoyaProvider<Target> where Target:TargetType{
open var plugin:TdwMoyaPlugin!
let disposeBag = DisposeBag()
init(vc:UIViewController,existToken:Bool){
self.plugin = TdwMoyaPlugin(vc: vc)//调用自己的plugin
super.init( plugins: [self.plugin])
}
func requestTdw(target:Target,success: @escaping (_ JSON: JSON) -> Void, fail: @escaping (_ error:Error) -> Void){
self.rx.request(target).subscribe { event in//rxswift使用moya发送请求
print("event=",event)
switch event {
case .success(let response):
let data = response.data
let json = JSON(data)
success(json)
case .error(let error):
print(error)
fail(error)
}
}.disposed(by: disposeBag)
}
}
var provider = TdwMoyaProvider(vc: self, existToken: true)
provider.request(JiaZhang.login(param)) { json in
print("json=",json)
}