NetworkTools類(lèi)封裝
import UIKit
import Alamofire
import SwiftyJSON
/// 請(qǐng)求響應(yīng)狀態(tài)
///
/// - success: 響應(yīng)成功
/// - unusual: 響應(yīng)異常
/// - failure: 請(qǐng)求錯(cuò)誤
enum ResponseStatus: Int {
case success = 0
case unusual = 1
case failure = 3
}
/// 網(wǎng)絡(luò)請(qǐng)求回調(diào)閉包 status:響應(yīng)狀態(tài) result:JSON tipString:提示給用戶的信息
typealias NetworkFinished = (_ status: ResponseStatus, _ result: JSON?, _ tipString: String?) -> ()
class NetworkTools: NSObject {
/// 網(wǎng)絡(luò)工具類(lèi)單例
static let shared = NetworkTools()
var rootDomain: String {
#if DEBUG
return URL_ROOT_DOMAIN_DEBUG + URL_SUB_DOMAIN
#else
return URL_ROOT_DOMAIN_RELEASE + URL_SUB_DOMAIN
#endif
}
}
// MARK: - 基礎(chǔ)請(qǐng)求方法
extension NetworkTools {
// in view: UIView = UIApplication.shared.keyWindow!,title: String? = nil
/**
GET請(qǐng)求
- parameter URLString: urlString
- parameter parameters: 參數(shù)
- parameter finished: 完成回調(diào)
*/
func get(_ APIString: String, parameters: [String : Any]?, needHeaders: Bool = true, needLoading: Bool = false, finished: @escaping NetworkFinished) {
if needLoading {
HexaLoading.show(in: UIApplication.shared.keyWindow!)
}
let headers = needHeaders ? self.headers() : nil
DLog("\n??????\nRequest: \nURL: \(rootDomain + APIString)\nMethod: get\nHeaders:\(String(describing: headers))\nParameters: \(String(describing: parameters))\n??????")
Alamofire.request(rootDomain + APIString, method: .get, parameters: parameters, headers: headers).responseJSON { (response) in
self.handle(response: response, finished: finished, needLoading: needLoading)
}
}
/**
POST請(qǐng)求
- parameter URLString: urlString
- parameter parameters: 參數(shù)
- parameter finished: 完成回調(diào)
*/
func post(_ APIString: String, parameters: [String : Any]?, needHeaders: Bool = true, needLoading: Bool = false, finished: @escaping NetworkFinished) {
if needLoading {
HexaLoading.show()
}
let headers = needHeaders ? self.headers() : nil
DLog("\n??????\nRequest: \nURL: \(rootDomain + APIString)\nMethod: post\nHeaders:\(String(describing: headers))\nParameters: \(String(describing: parameters))\n??????")
Alamofire.request(rootDomain + APIString, method: .post, parameters: parameters, headers: headers).responseJSON { (response) in
self.handle(response: response, finished: finished, needLoading: needLoading)
}
}
/// 處理響應(yīng)結(jié)果
///
/// - Parameters:
/// - response: 響應(yīng)對(duì)象
/// - finished: 完成回調(diào)
fileprivate func handle(response: DataResponse<Any>, finished: @escaping NetworkFinished, needLoading: Bool) {
if needLoading {
HexaLoading.hide()
}
switch response.result {
case .success(let value):
let json = JSON(value)
DLog(json)
if json["code"].string == "OK" {
finished(.success, json, json["message"].string)
} else {
finished(.unusual, json, json["message"].string)
}
case .failure(let error):
DLog(error)
finished(.failure, nil, error.localizedDescription)
}
}
/// 獲取請(qǐng)求頭
///
/// - Returns: 字典-請(qǐng)求頭內(nèi)容
fileprivate func headers() -> Dictionary<String, String>! {
let acceptLanguage = Locale.preferredLanguages
.prefix(6)
.enumerated()
.map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode),q=\(quality)"
}
.joined(separator: ", ")
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
return "HEXA/iOS/" + (info["CFBundleShortVersionString"] as? String ?? "Unknown")
}
return "HEXA/iOS/Unknown"
}()
return [
"Accept-Encoding": "gzip;q=1.0, compress;q=0.5",
"Accept-Language": acceptLanguage,
"User-Agent": userAgent,
"X-App-OSVersion": UIDevice.systemVersionName,
"X-App-Device": UIDevice.machineModelName,
"X-User-AccessToken": UserDefaults.standard.string(forKey: ACCESSTOKEN_KEY) ?? ""
]
}
}
調(diào)用過(guò)程
NetworkTools.shared.get(URL_CHECKUPDATE, parameters: nil, needLoading: true) {
DLog($0)
DLog($1)
DLog($2)
}