Swift 網(wǎng)絡(luò)框架(Alamofire)

Alamofire https://github.com/Alamofire/Alamofire
封裝框架AlamofireHttpToos

//
//  AlamofireHttpTools.swift
//  Created by PIGROAD on 2020/1/14.
//  Copyright ? 2020年 PIGROAD All rights reserved.
//

import Foundation
import Alamofire

class AlamofireHttpTools {

    static let instance : AlamofireHttpTools = AlamofireHttpTools()
    var sessionManager : SessionManager
    init() {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 70
        sessionManager = SessionManager(configuration: configuration)
    }
    
    func download<T : APIResponse>(urlString:String, responseType: T.Type = T.self, parameters:Dictionary<String,Any>,httpHeaders:HTTPHeaders, completionHandler:@escaping (DefaultDataResponse?, Error?) -> ()) {
        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        do {
            let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
            request.httpBody = data
            
            sessionManager.request(url, method: .post, parameters: parameters, encoding: JSONEncoding(options: []), headers: httpHeaders).response { (response) in
                completionHandler(response, nil)
            }
        }catch let error {
            print(error)
        }
    }
    
    func httpHearderPost<T : APIResponse>(urlString:String, responseType: T.Type = T.self, parameters:Dictionary<String,Any>,httpHeaders:HTTPHeaders, completionHandler:@escaping (APIResponse?, Error?) -> ()) {
        if !(NetworkReachabilityManager()?.isReachable ?? false) {
            completionHandler(nil, ErrorCode.noNetwork)
        }
        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        do {
            let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
            request.httpBody = data
            sessionManager.request(url, method: .post, parameters: parameters, encoding: JSONEncoding(options: []), headers: httpHeaders).validate(statusCode: [200]).responseJSON { (response) in
                print("API Start...")
                print("API call: \(request.urlRequest?.url?.absoluteString ?? "nil")")
                print("API request:\(String(data:request.urlRequest!.httpBody!, encoding: .utf8))")
                print("API response:\(response.response)")
                print("API response:\(response.result.value ?? "nil")")
                print("API End...")
                switch response.result {
                case .success:
                    let data = response.data!
                    if let responseObject = self.decodeWithType(type: responseType, data: data) {
                        completionHandler(responseObject, nil)
                    } else if let obj = self.decodeWithType(type: APIResponse.self, data: data) {
                        completionHandler(obj, nil)
                    } else if let obj = self.decodeWithType(type: SessionError.self, data: data) {
                        completionHandler(nil, obj)
                    } else {
                        completionHandler(nil, ErrorCode.responseInvalid)
                    }
                case .failure(let error):
                    print(response.response?.statusCode)
                    print("call http ERROR \(response.response?.statusCode ?? 0)")
                    completionHandler(nil, HttpError(code: response.response?.statusCode ?? 0))
                }
            }
        } catch {
            print(error)
        }
    }
    
    func decodeWithType<T: Codable>(type: T.Type, data: Data) -> T? {
        do {
            let decoder = JSONDecoder()
            let responseObject = try decoder.decode(type, from: data)
            return responseObject
            
        } catch let error {
            print("Fail to decode to type\(type): \(error.localizedDescription)")
            return nil
        }
    }
    
    
    /// Makes a post call to the given url and gets a completion callback after getting aresponse
    /// - parameter urlString: The url to be called
    /// - parameter responseType: The object type when getting the callback, should be a subclass of APIResponse otherwise it will return error while deserialising
    /// - parameter parameters: parameters to be used
    func httpPost<T : APIResponse>(urlString:String, responseType: T.Type = T.self, parameters:Dictionary<String,Any>, completionHandler:@escaping (APIResponse?, Error?) -> ()) {
        
        let url = URL(string: urlString)!
        //let jsonData = parameters.data(using: .utf8, allowLossyConversion: false)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        
        let data = try? JSONSerialization.data(withJSONObject: parameters, options: [])
        request.httpBody = data
        
        sessionManager.request(request).responseJSON {
            (response) in
            switch response.result {
            case .success:
                do {
                    let decoder = JSONDecoder()
                    let responseObject = try decoder.decode(responseType , from: response.data!)
                    completionHandler(responseObject, nil)
                } catch let e {
                    print(e)
                    completionHandler(nil, e)
                }
                print(response.result.value)
            case .failure(let error):
                print("call http ERROR")
                completionHandler(nil, error)
            }
        }
    }
    
    func httpGet<T : APIResponse>(urlString:String, responseType: T.Type = T.self, completionHandler:@escaping (APIResponse?, Error?) -> ()) /*(urlString:String, completionHandler:@escaping (NSDictionary?, Error?) -> ())*/{
        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.get.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        sessionManager.request(request).responseJSON {
            (response) in
            switch response.result {
            case .success:
                do {
                    let decoder = JSONDecoder()
                    let responseObject = try decoder.decode(responseType , from: response.data!)
                    
                    completionHandler(responseObject, nil)
                } catch let e {
                    completionHandler(nil, e)
                }
                print(response.result)
            case .failure(let error):
                print("call http ERROR")
                completionHandler(nil, error)
            }
        }
    }
    
    func httpPut (urlString:String, completionHandler:@escaping (NSDictionary?, Error?) -> ()){
        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.put.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        sessionManager.request(request).responseJSON {
            (response) in
            switch response.result {
            case .success:
                print(response.result.value)
                completionHandler(response.result.value as! NSDictionary, nil)
            case .failure:
                print("call http ERROR")
            }
        }
    }
}

APIResponse 參數(shù)返回體 根據(jù)項(xiàng)目具體而設(shè)置

class APIResponse: Codable {
    var resultCode : String
    var resultMessage : String
    var resultCause : String?
    
    var isSuccess : Bool {      
        return resultCode == "0"
    }
    
    static func errorMessage(response: APIResponse?, error: Error?) -> String{
        if let error = error as? HttpError {
            return error.errorMsg
        }
        
        if let response = response, !response.isSuccess {
            let buildVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
            
            var errorMsg : String
            if true { // TODO: Add is debug checking here
                return ErrorCode.getErrorMsg(code: response.resultCode)
            } else {
                return "\(Date().logString()) \(Constants.appVersion)(\(buildVersion ?? "")) \n \(response.resultCode) \(response.resultMessage)"
            }
        } else if let response = response as? AMLCheckResponse {
            if response.data?.dowJonesResult == "REJECT" {
                if response.data?.countrySanctionFlag == "Y" {
                    let errorMsg = ErrorCode.getErrorMsg(code: ErrorCode.onboardingRejected.rawValue)
                    return errorMsg
                }
            }
        }
        if let error = error as? ErrorCode {
            return error.localizedDescription
        } else {
            return error?.localizedDescription ?? "Error"
        }
        
        return "Error"
    }
}

模擬請求APIRequest

protocol APIRequest {
    var url : String {get}
    var requestParam : [String : Any]? {get set}
    var response : APIResponse? {get set}
    var httpHeaders : [String: String]? {get set}
    var error : Error? {get set}
    var retryCount : Int {get set}
    var completion : ((APIResponse?, Error?) -> Void)? {get set}
    func makeRequest()
}

請求方法SmsGeneration

import Foundation
class SmsGeneration : APIRequest {
  var url: String {return Domain.FCMS.url + Constants.sms_api + "generation"}
  var requestParam: [String : Any]?
  var response: APIResponse?
  var error: Error?
  var httpHeaders : [String: String]?
  var retryCount: Int = 0
  var completion: ((APIResponse?, Error?) -> Void)?
  
  func makeRequest() {
      AlamofireHttpTools.instance.httpHearderPost(urlString: self.url,responseType: SessionTokenResponse.self, parameters: self.requestParam!, httpHeaders: self.httpHeaders!) { (response, error) in
          self.response = response
          self.error = error
          self.completion?(response,error)
          print("sms :\(self.requestParam)")
      }
  }
  
  var msisdn : String
  
  init(msisdn: String) {
      self.msisdn = "852" + msisdn
      httpHeaders = APIRequestParamConstructor.baseHttpHeader(msisdn: self.msisdn)
      requestParam = APIRequestParamConstructor.newbaseRequestParam()
      requestParam!["data"] = [
          "deviceId" : "DeviceID",
          "language" : "EN",
          "clientIPAddress" : "xxx.xx.xxx.xx"
      ]
}
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市稽寒,隨后出現(xiàn)的幾起案子庙曙,更是在濱河造成了極大的恐慌媳板,老刑警劉巖染厅,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件痘绎,死亡現(xiàn)場離奇詭異,居然都是意外死亡肖粮,警方通過查閱死者的電腦和手機(jī)孤页,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來涩馆,“玉大人行施,你說我怎么就攤上這事』昴牵” “怎么了蛾号?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長涯雅。 經(jīng)常有香客問我鲜结,道長,這世上最難降的妖魔是什么活逆? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任精刷,我火速辦了婚禮,結(jié)果婚禮上蔗候,老公的妹妹穿的比我還像新娘贬养。我一直安慰自己,他們只是感情好琴庵,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布误算。 她就那樣靜靜地躺著,像睡著了一般迷殿。 火紅的嫁衣襯著肌膚如雪儿礼。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天庆寺,我揣著相機(jī)與錄音蚊夫,去河邊找鬼。 笑死懦尝,一個胖子當(dāng)著我的面吹牛知纷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播陵霉,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼琅轧,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了踊挠?” 一聲冷哼從身側(cè)響起乍桂,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后睹酌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體权谁,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年憋沿,在試婚紗的時候發(fā)現(xiàn)自己被綠了旺芽。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡辐啄,死狀恐怖采章,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情则披,我是刑警寧澤共缕,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布洗出,位于F島的核電站士复,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏翩活。R本人自食惡果不足惜阱洪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望菠镇。 院中可真熱鬧冗荸,春花似錦、人聲如沸利耍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽隘梨。三九已至程癌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間轴猎,已是汗流浹背嵌莉。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捻脖,地道東北人。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓可婶,卻偏偏與公主長得像沿癞,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子矛渴,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容