|
@@ -10,7 +10,7 @@ import Alamofire
|
|
|
import UIKit
|
|
|
|
|
|
// 默认超时时间
|
|
|
-public let timeoutInterval: TimeInterval = 30
|
|
|
+public let bf_timeoutInterval: TimeInterval = 30
|
|
|
|
|
|
// MARK: - 错误
|
|
|
|
|
@@ -39,8 +39,8 @@ public class SWNetRequest: NSObject {
|
|
|
|
|
|
static let sessionManager: Session? = {
|
|
|
let configuration = URLSessionConfiguration.default
|
|
|
- configuration.timeoutIntervalForRequest = timeoutInterval
|
|
|
- return Session(configuration: configuration, delegate: SessionDelegate(), serverTrustManager: nil)
|
|
|
+ configuration.timeoutIntervalForRequest = bf_timeoutInterval
|
|
|
+ return Session(configuration: configuration, delegate: SessionDelegate(), rootQueue: DispatchQueue(label: "org.alamofire.session.rootQueue"), startRequestsImmediately: true, requestQueue: nil, serializationQueue: nil, interceptor: CMRequestRetrier(), serverTrustManager: nil, redirectHandler: nil, cachedResponseHandler: nil, eventMonitors: [])
|
|
|
}()
|
|
|
|
|
|
static let reTrySessionManager: Session? = {
|
|
@@ -50,59 +50,60 @@ public class SWNetRequest: NSObject {
|
|
|
}()
|
|
|
|
|
|
/// get请求
|
|
|
- public class func getRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
|
|
|
+ public class func getRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = bf_timeoutInterval, response: @escaping completeHander) {
|
|
|
requestData(method: .get, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
|
|
|
response(responseObject, error, timeline)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// post请求
|
|
|
- public class func postRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
|
|
|
+ public class func postRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = bf_timeoutInterval, response: @escaping completeHander) {
|
|
|
requestData(method: .post, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
|
|
|
response(responseObject, error, timeline)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// put请求
|
|
|
- public class func putRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
|
|
|
+ public class func putRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = bf_timeoutInterval, response: @escaping completeHander) {
|
|
|
requestData(method: .put, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
|
|
|
response(responseObject, error, timeline)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// delete请求
|
|
|
- public class func deleteRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
|
|
|
+ public class func deleteRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = bf_timeoutInterval, response: @escaping completeHander) {
|
|
|
requestData(method: .delete, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
|
|
|
response(responseObject, error, timeline)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// head请求
|
|
|
- public class func headRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
|
|
|
+ public class func headRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = bf_timeoutInterval, response: @escaping completeHander) {
|
|
|
requestData(method: .head, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
|
|
|
response(responseObject, error, timeline)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// 网络请求
|
|
|
- fileprivate class func requestData(method: HTTPMethod, encoding: ParameterEncoding, url: String, parames: [String: Any]?, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
|
|
|
+ fileprivate class func requestData(method: HTTPMethod, encoding: ParameterEncoding, url: String, parames: [String: Any]?, timeoutInterval _: TimeInterval = bf_timeoutInterval, response: @escaping completeHander) {
|
|
|
if !bf_validURL(url: url) {
|
|
|
response(nil, PQError(msg: "非法地址", code: 0), nil)
|
|
|
return
|
|
|
}
|
|
|
debugPrint("网络请求-发起:url = \(url),parames = \(parames ?? [:])")
|
|
|
- AF.request(url, method: method, parameters: parames, encoding: encoding, headers: nil, requestModifier: { request in
|
|
|
- request.timeoutInterval = timeoutInterval
|
|
|
- }).validate().responseJSON { jsonResponse in
|
|
|
+
|
|
|
+ sessionManager?.request(url, method: method, parameters: parames, encoding: encoding, headers: nil, requestModifier: { request in
|
|
|
+ request.timeoutInterval = bf_timeoutInterval
|
|
|
+ }).responseJSON { jsonResponse in
|
|
|
switch jsonResponse.result {
|
|
|
case .success:
|
|
|
let jsonData: Any = try! JSONSerialization.jsonObject(with: jsonResponse.data!, options: JSONSerialization.ReadingOptions.mutableContainers)
|
|
|
debugPrint("网络请求-成功:url = \(jsonResponse.request?.url?.absoluteString ?? ""),jsonData = \(jsonData)")
|
|
|
response(jsonData, nil, jsonResponse.metrics?.taskInterval.duration)
|
|
|
- case .failure:
|
|
|
- let code: Int? = jsonResponse.response?.statusCode
|
|
|
- response(nil, PQError(msg: (code == -1009 || code == -1001) ? "网络不可用" : jsonResponse.error?.localizedDescription, code: code ?? 10001), jsonResponse.metrics?.taskInterval.duration)
|
|
|
- debugPrint("网络请求-失败:url = \(jsonResponse.request?.url?.absoluteString ?? ""),error = \(String(describing: jsonResponse.error))")
|
|
|
+ case let .failure(error):
|
|
|
+ let errorResult = dealWithError(error: error)
|
|
|
+ response(nil, PQError(msg: errorResult.msg, code: errorResult.code), jsonResponse.metrics?.taskInterval.duration)
|
|
|
+ debugPrint("网络请求-失败:url = \(jsonResponse.request?.url?.absoluteString ?? ""),error = \(String(describing: jsonResponse.error?.localizedDescription))")
|
|
|
}
|
|
|
}
|
|
|
}
|
|
@@ -190,4 +191,83 @@ public class SWNetRequest: NSObject {
|
|
|
public class func bf_urlDecoded(url: String) -> String {
|
|
|
return url.removingPercentEncoding ?? ""
|
|
|
}
|
|
|
+
|
|
|
+ public class func dealWithError(error: Error?) -> (code: Int, msg: String?) {
|
|
|
+ var code: errorCode = .nomal
|
|
|
+ var msg: String? = error?.localizedDescription
|
|
|
+ if let error = error as? AFError {
|
|
|
+ switch error {
|
|
|
+ case let .invalidURL(url):
|
|
|
+ print("网球请求-处理错误:Invalid URL: \(url) - \(error.localizedDescription)")
|
|
|
+ code = .valideUrl
|
|
|
+ msg = "请求地址检验失败"
|
|
|
+ case let .parameterEncodingFailed(reason):
|
|
|
+ print("网球请求-处理错误:parameterEncodingFailed \(error.localizedDescription),Reason: \(reason)")
|
|
|
+ case let .multipartEncodingFailed(reason):
|
|
|
+ print("网球请求-处理错误:multipartEncodingFailed: \(error.localizedDescription),\(reason)")
|
|
|
+ case let .responseValidationFailed(reason):
|
|
|
+ print("网球请求-处理错误:responseValidationFailed: \(error.localizedDescription),Reason: \(reason)")
|
|
|
+ switch reason {
|
|
|
+ case .dataFileNil, .dataFileReadFailed:
|
|
|
+ print("网球请求-处理错误:Downloaded file could not be read")
|
|
|
+ case let .missingContentType(acceptableContentTypes):
|
|
|
+ print("网球请求-处理错误:Content Type Missing: \(acceptableContentTypes)")
|
|
|
+ case let .unacceptableContentType(acceptableContentTypes, responseContentType):
|
|
|
+ print("网球请求-处理错误:Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
|
|
|
+ case let .unacceptableStatusCode(code):
|
|
|
+ print("网球请求-处理错误:Response status code was unacceptable: \(code)")
|
|
|
+ case let .customValidationFailed(error: error):
|
|
|
+ print("网球请求-处理错误:customValidationFailed: \(error)")
|
|
|
+ }
|
|
|
+ case let .responseSerializationFailed(reason):
|
|
|
+ print("网球请求-处理错误:Response serialization failed: \(error.localizedDescription)")
|
|
|
+ print("Failure Reason: \(reason)")
|
|
|
+ case let .createUploadableFailed(error: error):
|
|
|
+ print("网球请求-处理错误:createUploadableFailed: \(error.localizedDescription)")
|
|
|
+ case let .createURLRequestFailed(error: error):
|
|
|
+ print("createURLRequestFailed: \(error.localizedDescription)")
|
|
|
+ case let .downloadedFileMoveFailed(error: error, source: source, destination: destination):
|
|
|
+ print("网球请求-处理错误:downloadedFileMoveFailed: \(error.localizedDescription)")
|
|
|
+ case .explicitlyCancelled:
|
|
|
+ print("网球请求-处理错误:explicitlyCancelled: \(error.localizedDescription)")
|
|
|
+ case let .parameterEncoderFailed(reason: reason):
|
|
|
+ print("网球请求-处理错误:parameterEncoderFailed: \(error.localizedDescription)")
|
|
|
+ case let .requestAdaptationFailed(error: error):
|
|
|
+ print("网球请求-处理错误:requestAdaptationFailed: \(error.localizedDescription)")
|
|
|
+ case let .requestRetryFailed(retryError: retryError, originalError: originalError):
|
|
|
+ print("网球请求-处理错误:requestRetryFailed: retryError = \(retryError),originalError = \(originalError)\(error.localizedDescription)")
|
|
|
+ case let .serverTrustEvaluationFailed(reason: reason):
|
|
|
+ print("网球请求-处理错误:serverTrustEvaluationFailed: - \(error.localizedDescription)")
|
|
|
+ case .sessionDeinitialized:
|
|
|
+ print("网球请求-处理错误:sessionDeinitialized: \(error.localizedDescription)")
|
|
|
+ case let .sessionInvalidated(error: error):
|
|
|
+ print("网球请求-处理错误:sessionInvalidated: \(error?.localizedDescription)")
|
|
|
+ case let .sessionTaskFailed(error: error):
|
|
|
+ print("网球请求-处理错误:sessionTaskFailed:error = \(error) \(error.localizedDescription)")
|
|
|
+ code = errorCode.init(rawValue: (error as? NSError)?.code ?? 1) ?? .nomal
|
|
|
+ if code == .netLost || code == .tomeOut {
|
|
|
+ msg = "网络不给力"
|
|
|
+ }
|
|
|
+ case let .urlRequestValidationFailed(reason: reason):
|
|
|
+ print("网球请求-处理错误:urlRequestValidationFailed: \(error.localizedDescription)")
|
|
|
+ }
|
|
|
+ print("网球请求-处理错误:Underlying error: \(String(describing: error.underlyingError))")
|
|
|
+ } else {
|
|
|
+ print("网球请求-处理错误:Unknown error: \(String(describing: error))")
|
|
|
+ }
|
|
|
+ return (code.rawValue, msg)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+class CMRequestRetrier: RequestInterceptor {
|
|
|
+ func retry(_: Request, for _: Session, dueTo _: Error, completion: @escaping (RetryResult) -> Void) {
|
|
|
+ completion(.doNotRetry)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+enum errorCode: Int {
|
|
|
+ case nomal = 1
|
|
|
+ case valideUrl = 2
|
|
|
+ case tomeOut = -1001
|
|
|
+ case netLost = -1009
|
|
|
}
|