溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

swift中怎么使用Alamofire+Moya+ObjectMapper

發(fā)布時(shí)間:2021-11-02 09:08:27 來(lái)源:億速云 閱讀:183 作者:iii 欄目:編程語(yǔ)言

這篇文章主要介紹“swift中怎么使用Alamofire+Moya+ObjectMapper”,在日常操作中,相信很多人在swift中怎么使用Alamofire+Moya+ObjectMapper問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”swift中怎么使用Alamofire+Moya+ObjectMapper”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

項(xiàng)目開發(fā)中的接口比較多,在使用moya時(shí)會(huì)使用多個(gè)類,為避免一些代買的重復(fù)書寫,做了一些封裝處理,網(wǎng)絡(luò)使用Alamofire,數(shù)據(jù)解析使用Moya-ObjectMapper

  • 首先是對(duì)返回?cái)?shù)據(jù)統(tǒng)一處理的模型

import ObjectMapper
import Moya

///具體問(wèn)題具體分析,應(yīng)根據(jù)接口實(shí)際返回?cái)?shù)據(jù)結(jié)構(gòu)來(lái)定
class ResponseModel: NSObject,Mappable {
    
    /// 返回碼
    var code:Int = 0
    /// 信息
    var message:String = ""
    /// 數(shù)據(jù)
    var data:Any?
    
    override init() {super.init()}
    
    init(_ code: Int, message:String, data:Any? = nil) {
        self.code = code
        self.message = message
        self.data = data
    }
    
    class func success(_ data:Any) ->ResponseModel{
        return ResponseModel(200, message: "SUCCESS", data: data)
    }
    
    class func faild(_ message:String? = "FAILD") ->ResponseModel{
        return ResponseModel(400, message: message ?? "FAILD", data: nil)
    }
    
    required init?(map: Map) {}
    
    //若接口返回的是msg,則應(yīng)當(dāng)這么寫message <- map["msg"],或則直接將屬性message修改為msg,然后msg <- map["msg"]
    func mapping(map: Map) {
        code <- map["code"]
        message <- map["message"]
        data <- map["data"]
    }
}
  • 然后是對(duì)返回?cái)?shù)據(jù)的統(tǒng)一 處理工具

import Moya

class NetWorkManager {
    
    /// 處理成功的返回結(jié)果
    static func getResponse(_ success:Moya.Response) ->ResponseModel {
        var responseModel:ResponseModel = ResponseModel()
        do {
            responseModel =  try success.mapObject(ResponseModel.self)
            //這里得注意下,有時(shí)候后臺(tái)返回的數(shù)據(jù)類型無(wú)法解析,就得做其他特殊處理
            //之前遇到過(guò),由于數(shù)據(jù)返回的編碼方式不同,導(dǎo)致無(wú)法解析,我便使用了下面的方法
//            let cfEnc = CFStringEncodings.GB_18030_2000//具體問(wèn)題具體分析哈
//            let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
//            if let str = String(data: success.data, encoding: String.Encoding(rawValue: enc)), let obj = str.data(using: .utf8), let dic = try JSONSerialization.jsonObject(with: obj, options: .mutableContainers) as? [String: Any],let res = ResponseModel(JSON: dic) {
//                responseModel = res
//            }else{
//                responseModel.code = 400
//                responseModel.message = "無(wú)法解析網(wǎng)絡(luò)數(shù)據(jù)"
//            }
        }catch{
            responseModel.code = 400
            responseModel.message = "無(wú)法解析網(wǎng)絡(luò)返回?cái)?shù)據(jù)"
        }
        //TODO: 根據(jù)各自業(yè)務(wù)需求,可對(duì)一些返回結(jié)果做出特殊處理????
        if responseModel.code == 200 ,responseModel.message == "SUCCESS",responseModel.data == nil {
            responseModel.message = "沒(méi)有更多了"
        }
        return responseModel
    }
    
    /// 處理失敗的返回結(jié)果
    static func getResponse(_ error:MoyaError) ->ResponseModel {
        let responseModel:ResponseModel = ResponseModel()
        responseModel.code = 500
        responseModel.message = error.errorDescription ?? "網(wǎng)絡(luò)訪問(wèn)出錯(cuò)"
        return responseModel
    }

    /// 獲取請(qǐng)求頭
    ///
    /// - Parameter token: 是否包含token
    /// - Returns: <#return value description#>
    static func getHeaders(_ token:Bool = true) ->[String:String] {
        var result:[String:String] = ["Content-type" : "application/json"]
        if token {
            result["Token"] = "這里寫用戶的token"
        }
        result["其他key"] = "key對(duì)應(yīng)的value"
        return result
    }
}
  • 再對(duì)MoyaProvider進(jìn)行擴(kuò)展

    import Moya
    import Alamofire
    
    extension MoyaProvider {
        
        static func custom(
            endpointClosure: @escaping Moya.MoyaProvider<Target>.EndpointClosure = HZJMoyaTool<Target>.endpointClosure,
            requestClosure: @escaping Moya.MoyaProvider<Target>.RequestClosure = HZJMoyaTool<Target>.requestResultClosure,
            stubClosure: @escaping Moya.MoyaProvider<Target>.StubClosure = HZJMoyaTool<Target>.stubClosure,
            callbackQueue: DispatchQueue? = nil,
            session: Moya.Session = HZJMoyaTool<Target>.session(),
            plugins: [Moya.PluginType] = HZJMoyaTool<Target>.authPlugins(),
            trackInflights: Bool = false) -> MoyaProvider{
            return MoyaProvider.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, callbackQueue: callbackQueue, session: session, plugins: plugins, trackInflights: trackInflights)
        }
    
        func hzj_Request(_ target: Target, callbackQueue: DispatchQueue? = .none, progress: ProgressBlock? = .none, finishBlock:@escaping ((ResponseModel)->Void)) {
            self.request(target, callbackQueue: callbackQueue, progress: progress) { (result) in
                switch result {
                case let .success(response):
                    finishBlock(NetWorkManager.getResponse(response))
                case let .failure(error):
                    finishBlock(NetWorkManager.getResponse(error))
                }
            }
        }
    }


     

  • 其中的HZJMoyaTool類,其中的具體內(nèi)容,大家應(yīng)根據(jù)自己的項(xiàng)目而定

    struct HZJMoyaTool<Target: TargetType> {
        
        static func endpointClosure(for target: Target) -> Endpoint {
            let url = target.baseURL.appendingPathComponent(target.path).absoluteString
            let endpoint = Endpoint(url: url, sampleResponseClosure: {.networkResponse(200,target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers)
    //            endpoint.adding(newHTTPHeaderFields:["Content-Type" : "application/x-www-form-urlencoded","ECP-COOKIE" : ""])
            return endpoint
        }
        
        static func requestResultClosure(for endpoint: Endpoint, closure: MoyaProvider<Target>.RequestResultClosure) {
            do {
                var urlRequest = try endpoint.urlRequest()
                urlRequest.timeoutInterval = 60//設(shè)置網(wǎng)絡(luò)超時(shí)時(shí)間
    //            urlRequest.cachePolicy = .returnCacheDataElseLoad
                closure(.success(urlRequest))
            } catch MoyaError.requestMapping(let url) {
                closure(.failure(MoyaError.requestMapping(url)))
            } catch MoyaError.parameterEncoding(let error) {
                closure(.failure(MoyaError.parameterEncoding(error)))
            } catch {
                closure(.failure(MoyaError.underlying(error, nil)))
            }
        }
        
        static func stubClosure(_: Target) -> Moya.StubBehavior {
    //        return Moya.StubBehavior.immediate//使用sampleData中返回的測(cè)試數(shù)據(jù)
            return Moya.StubBehavior.never
        }
        
        static func session() -> Session {
            let defaultSession = MoyaProvider<Target>.defaultAlamofireSession()
    //        let configuration = URLSessionConfiguration.default
    //        configuration.headers = defaultSession.sessionConfiguration.headers
    //        configuration.httpAdditionalHeaders = defaultSession.sessionConfiguration.httpAdditionalHeaders
            let configuration = defaultSession.sessionConfiguration
            if let path: String = Bundle.main.path(forResource: "xxx", ofType: "cer") {
                ///添加證書
                do {
                    let certificationData = try Data(contentsOf: URL(fileURLWithPath: path)) as CFData
                    if let certificate = SecCertificateCreateWithData(nil, certificationData){
                        let certificates: [SecCertificate] = [certificate]
                        let policies: [String: ServerTrustEvaluating] = ["domain": PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: true, performDefaultValidation: true, validateHost: true)]
                        let manager = ServerTrustManager(allHostsMustBeEvaluated: false, evaluators: policies)
                        return Session(configuration: configuration, serverTrustManager: manager)
                    }
                } catch {
                    return Session(configuration: configuration)
                }
            }
            return Session(configuration: configuration)
        }
        
        static func authPlugins() -> [Moya.PluginType] {
            return []
    //        return [AccessTokenPlugin{_ in User.shared.token}]
        }
    }


     

  • 最后再舉個(gè)使用例子吧 

    import Moya
    
    let LoginLogManager = MoyaProvider<LoginLogAPI>.custom()
    
    enum LoginLogAPI {
        ///添加登錄日志(type:0-web 1-app)
        case addLoginLog(type:Int)
        ///子模塊,將部分接口抽離出去
        case childApi(child:ChildAPI)
    }
    
    extension LoginLogAPI:TargetType {
        var baseURL: URL {
            switch self {
            case . childApi(child: let child):
                return child.baseURL
            default:
                return URL(string: AppRootApi + "/api/appHtLoginLog/")!
            }
        }
        
        var path: String {
            switch self {
            case . childApi(child: let child):
                return child.path
            case .addLoginLog(type: _):
                return "addLoginLog"
            }
        }
        
        var method: Moya.Method {
            switch self {
            case . childApi(child: let child):
                return child.method
            default:
                return .post
            }
        }
        
        var sampleData: Data {
            switch self {
            case . childApi(child: let child):
                return child.sampleData
            default:
                return "{sampleDataKey:sampleDataValue}".data(using: String.Encoding.utf8)!
            }
        }
        
        var task: Task {
            var params:[String:Any] = [:]
            switch self {
            case . childApi(child: let child):
                return child.task
            case .addLoginLog(type: let type):
                params["type"] = type
                return .requestCompositeParameters(bodyParameters: [:], bodyEncoding: URLEncoding.httpBody, urlParameters: params)
            }
        }
        
        var headers: [String : String]? {
            switch self {
            case . childApi(child: let child):
                return child.headers
            default:
                return NetWorkManager.getHeaders(true)
            }
        }
    }


    當(dāng)模塊中接口較多時(shí),或者部分接口需要統(tǒng)一特殊處理時(shí),可以將部分接口抽出來(lái),使用子模塊

    ///子模塊
    enum ChildAPI {
        case refreshInfo(name:String)
    }
    
    extension ChildAPI:TargetType {
        var baseURL: URL {
            return URL(string: AppRootApi + "/api/appHtLoginLog/")!
        }
        
        var path: String {
            switch self {
            case .refreshInfo(name: _):
                return "refreshInfo"
            }
        }
        
        var method: Moya.Method {
            switch self {
            default:
                return .post
            }
        }
        
        var sampleData: Data {
            return "{sampleDataKey:sampleDataValue}".data(using: String.Encoding.utf8)!
        }
        
        var task: Task {
            var params:[String:Any] = [:]
            switch self {
            case .refreshInfo(name: let name):
                params["name"] = name
                return .requestParameters(parameters: params, encoding: JSONEncoding.default)
            }
        }
        
        var headers: [String : String]? {
            switch self {
            default:
                return NetWorkManager.getHeaders(false)
            }
        }
    }


     

  • 使用接口就這樣

        func test() {
            LoginLogManager.hzj_Request(.addLoginLog(type: 1)) { [weak self](responseModel) in
                guard let strongSelf = self else { return }
                if responseModel.code == 200 {
                    print("成功")
                }else{
                    print("失敗")
                }
            }
        }
    
        func test2() {
            LoginLogManager.hzj_Request(.childApi(.refreshInfo(name: "test"))) { [weak self](responseModel) in
                guard let strongSelf = self else { return }
                if responseModel.code == 200 {
                    print("成功")
                }else{
                    print("失敗")
                }
            }
        }



到此,關(guān)于“swift中怎么使用Alamofire+Moya+ObjectMapper”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI