Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Alamofire+Moya+ObjectMapper in swift

Shulou Source: shulou.com Published: 2022-06-02 19:39:46 09月23日 Update

This article mainly introduces "how to use Alamofire+Moya+ObjectMapper in swift". In daily operation, I believe many people have doubts about how to use Alamofire+Moya+ObjectMapper in swift. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use Alamofire+Moya+ObjectMapper in swift"! Next, please follow the editor to study!

There are many interfaces in the development of the project, and multiple classes will be used when using moya. In order to avoid repeated writing of some purchasing agents, some encapsulation has been done, the network uses Alamofire, and data parsing uses Moya-ObjectMapper.

The first is the model of unified processing of the returned data.

According to the specific analysis of import ObjectMapperimport Moya/// specific problems, class ResponseModel should be determined according to the actual data structure returned by the API: NSObject,Mappable {/ return code var code:Int = 0 / Information var message:String = "" / data 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) {} / / if the API returns msg You should write message 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))}

The HZJMoyaTool class, the specific content of which should be determined according to your own project.

Struct HZJMoyaTool {static func endpointClosure (for target: Target)-> Endpoint {let url = target.baseURL.appendingPathComponent (target.path). AbsoluteString let endpoint = Endpoint (url: url, sampleResponseClosure: {.networkResponse (200target. 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.RequestResultClosure) {do {var urlRequest = try endpoint.urlRequest () urlRequest.timeoutInterval = 60max / set network timeout / / urlRequest.cachePolicy = .SecretnCacheDataElseLoad closure (.su ccess (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// uses the test data returned in sampleData return Moya.StubBehavior.never} static func session ()-> Session {let defaultSession = MoyaProvider.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") {/ / add certificate 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}]}}

Finally, let's give an example of using it.

Import Moyalet LoginLogManager = MoyaProvider.custom () enum LoginLogAPI {/ / add login log (type:0-web 1-app) case addLoginLog (type:Int) / sub-module, pull some interfaces out of 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)}

When there are many interfaces in the module, or when some interfaces need unified special treatment, you can extract some of the interfaces and use sub-modules.

/ / Sub-module 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)}

Use the interface, that's it.

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

At this point, the study on "how to use Alamofire+Moya+ObjectMapper in swift" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Data interfaces processing networks modules learning special successful more results parts problems unification methods projects analysis help different practical next Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Microsoft Shulou Information Shulou Tech Info NVidia