Swift 网络框架(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(urlString:String, responseType: T.Type = T.self, parameters:Dictionary,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(urlString:String, responseType: T.Type = T.self, parameters:Dictionary,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(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(urlString:String, responseType: T.Type = T.self, parameters:Dictionary, 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(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 参数返回体 根据项目具体而设置

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"
      ]
}
}

你可能感兴趣的:(Swift 网络框架(Alamofire))