importUIKit
import Moya
/// 请求是否显示HUD
var SHOW_HUD: Bool = true
class RequestPlugin: PluginType {
funcwillSend(_request:RequestType, target:TargetType) {
if SHOW_HUD {
HUDManager.showLoading()
}else{
HUDManager.dismiss()
}
}
func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
HUDManager.dismiss()
switch result {
case let .success(response):
#if DEBUG || DEBUG_DEV || DEBUG_SIT || DEBUG_UAT || DEBUG_PRD
if let jsonString =try? response.mapString() {
Log(response.response?.url ??"")
Log(jsonString)
}
#endif
guard((200...209) ~= response.statusCode)else{
HUDManager.showTipText("netError".localized())
return
}
case.failure(_):
HUDManager.showTipText("netError".localized())
break
}
}
}
~service
import Foundation
import Moya
import Alamofire
struct Service {
private init() {}
private static let userProvider= MoyaProvider(session:AlamofireManager.shared, plugins: [RequestPlugin()])
//用户provider
static func UserProvider(_ show: Bool = true) -> MoyaProvider<UserService> {
SHOW_HUD = show
return userProvider
}
private static let trendProvider= MoyaProvider(session:AlamofireManager.shared, plugins: [RequestPlugin()])
//社区provider
static func TrendProvider(_ show: Bool = true) -> MoyaProvider<TrendService> {
SHOW_HUD = show
return trendProvider
}
}
class AlamofireManager: Alamofire.Session {
static let shared: AlamofireManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders= HTTPHeaders.default.dictionary
configuration.timeoutIntervalForRequest=30
configuration.timeoutIntervalForResource = 60
return AlamofireManager(configuration: configuration)
}()
}
------------------usrservice -- start ---------------------------
importFoundation
import Moya
enum UserService {
///登录注册
caseuserLogin(mobilePhone:String, validateCode:String)
}
extension UserService: TargetType {
var baseURL:URL{
return URL(string: ServerMgr.shared.config.UserHost + ServerMgr.shared.config.UserGateway)!
}
var path:String{
switch self{
case.userLogin:
return "user/app/login"
case .vertifyPhone:
return "validateCode/getCode"
}
}
var method:Moya.Method{
switch self{
case .vertifyPhone,
.queryUser,
.testDriveList:
return .get
case .userLogin:
return .post
}
}
var task:Task{
switch self{
//发送短信验证码:
case .vertifyPhone(let mobilePhone,let messageType):
return .requestParameters(parameters: ["mobilePhone": mobilePhone,"messageType":messageType], encoding: URLEncoding.default)
case .sendSmsPhone(_):
return.requestParameters(parameters: [:], encoding: URLEncoding.default)
}
------------------usrservice -- end ---------------------------