您好,登錄后才能下訂單哦!
這篇文章主要介紹“swift中怎么使用Alamofire+Moya+ObjectMapper”,在日常操作中,相信很多人在swift中怎么使用Alamofire+Moya+ObjectMapper問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”swift中怎么使用Alamofire+Moya+ObjectMapper”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
項目開發中的接口比較多,在使用moya時會使用多個類,為避免一些代買的重復書寫,做了一些封裝處理,網絡使用Alamofire,數據解析使用Moya-ObjectMapper
首先是對返回數據統一處理的模型
import ObjectMapper import Moya ///具體問題具體分析,應根據接口實際返回數據結構來定 class ResponseModel: NSObject,Mappable { /// 返回碼 var code:Int = 0 /// 信息 var message:String = "" /// 數據 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,則應當這么寫message <- map["msg"],或則直接將屬性message修改為msg,然后msg <- map["msg"] func mapping(map: Map) { code <- map["code"] message <- map["message"] data <- map["data"] } }
然后是對返回數據的統一 處理工具
import Moya class NetWorkManager { /// 處理成功的返回結果 static func getResponse(_ success:Moya.Response) ->ResponseModel { var responseModel:ResponseModel = ResponseModel() do { responseModel = try success.mapObject(ResponseModel.self) //這里得注意下,有時候后臺返回的數據類型無法解析,就得做其他特殊處理 //之前遇到過,由于數據返回的編碼方式不同,導致無法解析,我便使用了下面的方法 // let cfEnc = CFStringEncodings.GB_18030_2000//具體問題具體分析哈 // 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 = "無法解析網絡數據" // } }catch{ responseModel.code = 400 responseModel.message = "無法解析網絡返回數據" } //TODO: 根據各自業務需求,可對一些返回結果做出特殊處理???? if responseModel.code == 200 ,responseModel.message == "SUCCESS",responseModel.data == nil { responseModel.message = "沒有更多了" } return responseModel } /// 處理失敗的返回結果 static func getResponse(_ error:MoyaError) ->ResponseModel { let responseModel:ResponseModel = ResponseModel() responseModel.code = 500 responseModel.message = error.errorDescription ?? "網絡訪問出錯" return responseModel } /// 獲取請求頭 /// /// - 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對應的value" return result } }
再對MoyaProvider進行擴展
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類,其中的具體內容,大家應根據自己的項目而定
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//設置網絡超時時間 // 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中返回的測試數據 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}] } }
最后再舉個使用例子吧
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) } } }
當模塊中接口較多時,或者部分接口需要統一特殊處理時,可以將部分接口抽出來,使用子模塊
///子模塊 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("失敗") } } }
到此,關于“swift中怎么使用Alamofire+Moya+ObjectMapper”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。