You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

150 lines
5.4 KiB

//
// HPNetworkProvider.swift
// HPlusFit
//
// Created by lemo. on 2019/8/31.
// Copyright © 2019 lemo. All rights reserved.
//
import Foundation
import Moya
///
private var requestTimeOut: Double = 30
typealias successBlock = (JSON) -> ()
typealias failureBlock = (MoyaError) -> ()
///
private let myEndpointClosure = { (target: APIManager) -> Endpoint in
var url = target.baseURL.absoluteString + target.path
switch target {
case .downLoad:
url = target.path
default: break
}
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let tempUrl = NSURL(string: url), let ip = appDelegate.httpdns?.getIpByHostAsync(tempUrl.host) {
// HTTPDNSIPURLHOST
url = url.replacingOccurrences(of: tempUrl.host ?? "", with: ip)
}
}
let endPoint = Endpoint(url: url,
sampleResponseClosure: { .networkResponse(200, target.sampleData) },
method: target.method,
task: target.task,
httpHeaderFields: target.headers)
return endPoint
}
///
private let myRequestClosure = { (endpoint: Endpoint, closure: @escaping MoyaProvider.RequestResultClosure) -> Void in
do {
var request = try endpoint.urlRequest()
//
request.timeoutInterval = requestTimeOut
//
if let requestData = request.httpBody {
LFLogs("[网络通信] 请求地址: \(request.url!)" + "\n" + "请求类型: \(request.httpMethod ?? "")" + "\n" + "请求参数: \(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
}else{
LFLogs("[网络通信] 请求地址: \(request.url!)" + "\n" + "请求参数: \(String(describing: request.httpMethod))")
}
closure(.success(request))
} catch {
closure(.failure(MoyaError.underlying(error, nil)))
}
}
/// NetworkActivityPlugin
let myNetworkActivityPlugin = NetworkActivityPlugin { (changeType, HPAPIManager) in
// targetType
switch(changeType){
case .began:
LFLogs("[网络通信] 开始请求")
case .ended:
LFLogs("[网络通信] 结束请求")
}
}
/// NetworkLoggerPlugin
let myNetworkLoggerPlugin = NetworkLoggerPlugin(verbose: true, cURL: true, output: { (separator: String, terminator: String, items: Any...) in
}, requestDataFormatter: { (requestData: Data) -> (String) in
return ""
}, responseDataFormatter: { (responseData: Data) -> (Data) in
return Data()
})
/// MoyaProvider
private let provider = MoyaProvider<APIManager>(endpointClosure: myEndpointClosure, requestClosure: myRequestClosure, plugins: [myNetworkActivityPlugin, myNetworkLoggerPlugin])
private let disposeBag = DisposeBag()
///
///
/// - Parameter target:
/// - Returns: JSON
func ProviderRequest(_ target: APIManager) -> Observable<JSON> {
return Observable.create({ (observer) -> Disposable in
provider.rx.request(target)
.filterSuccessfulStatusCodes()
.mapJSON()
.subscribe(onSuccess: { (response) in
let json = JSON(response)
LFLogs("[网络通信] 回复 \(String(describing: target.path)) \(json)")
let code = json["code"].intValue
if code == 1 {
observer.onNext(json)
}else {
SVProgressHUD.showError(withStatus: MultiLanguageKey.networkError.localized)
}
}, onError: { (error) in
SVProgressHUD.showError(withStatus: MultiLanguageKey.networkError.localized)
observer.onError(MoyaError.underlying(error, nil))
})
.disposed(by: disposeBag)
return Disposables.create()
})
}
///
///
/// - Parameter target:
/// - Returns: JSON
func ProviderRequestDownload(_ target: APIManager) -> Observable<Data> {
return Observable.create({ (observer) -> Disposable in
provider.rx.request(target)
.filterSuccessfulStatusCodes()
.subscribe(onSuccess: { (response) in
observer.onNext(response.data)
}, onError: { (error) in
SVProgressHUD.showError(withStatus: "网络连接异常,请稍后重试".localized)
observer.onError(MoyaError.underlying(error, nil))
})
.disposed(by: disposeBag)
return Disposables.create()
})
}
///
///
/// - Parameter target:
/// - Returns: JSON
func ProviderRequestDownloadWithProgress(_ target: APIManager) -> Observable<ProgressResponse> {
return Observable.create({ (observer) -> Disposable in
provider.rx.requestWithProgress(target)
.subscribe(onNext: { (response) in
observer.onNext(response)
}, onError: { (error) in
SVProgressHUD.showError(withStatus: "网络连接异常,请稍后重试".localized)
observer.onError(MoyaError.underlying(error, nil))
}, onCompleted: {
observer.onCompleted()
})
.disposed(by: disposeBag)
return Disposables.create()
})
}