Swift Network request (MOYA)

Source: Internet
Author: User

When using Alamofire for network requests, I believe most of the students will encapsulate an abstract networklayer, such as "Apimanager" or "Networkmodel" and so on. But the location business function increases, will gradually mix various requests, is not clear, but Moya can solve this kind of problem well. Moya is encapsulated on a alamofire basis and is a highly customizable network layer that can be set up to meet specific requirements. The detailed introduction can refer to the official link of Moya, the structure chart is as follows:

Here's a look at some common uses of Moya:

(i) Create specific requests based on business requirements:

For example, now we need to write the relevant interface of the account, such as login, UserInfo. So first we have to create Accountservice:

enum Accountservice {    case  Login (phonenum:nsinteger,password:nsinteger)    case  Logout}

Then let Accountservice implement the TargetType protocol, defining the basic information required for the request:

extension Accountservice:targettype {var baseurl:url {returnURL (string: Servicebaseurl)!} var path:string {SwitchSelf { Case. Login (_, _):return "Accountservice/login"         Case. Logout:return "Accountservice/logout"}} var Method:Moya.Method {SwitchSelf { Case. Login (_, _):return. Post Case. Logout:return.Get}} var parameters: [String:any]? {        SwitchSelf { Case. Login (Let phonenum, let PassWord):return["Phonenum": Phonenum,"PassWord": PassWord] Case. Logout:returnNil}} var parameterencoding:parameterencoding {returnJsonencoding.default //Send parameters as JSON in Request body} var sampledata:data {return "". Data (using:. UTF8)!} var task:task {return. Request}}

As above we have completed the request for the network one endpoint . The Moya is then provided with a send requestProvider就完成了基本的使用:

Let Provider = moyaprovider<accountservice>()

Provider.request (. Login (phonenum:12345678901, password:123456)) {result in
            Switch result {case-let             . Success (response):                //...                .. Break Case-Let             . Failure (Error):                //...                .. Break            }        }   

(ii) Setting public request parameters via Httpheader

In actual development we may need to add some public request parameters in the request header, such as the version number used to identify some platform flags and identify the interface. You can define a endpoint closure,

Let Publicparamendpointclosure = {(target:accountservice)-endpoint<accountservice>inchLet URL=target.baseURL.appendingPathComponent (target.path). absolutestring Let Endpoint= Endpoint<accountservice> (Url:url, sampleresponseclosure: {. Networkresponse ( $, Target.sampledata)}, Method:target.method, Parameters:target.parameters, parameterencoding: target.parameterencoding)returnEndpoint.adding (newhttpheaderfields: ["X-platform":"IOS","x-interface-version":"1.0"])        }

You then create the requestedProvider把它添加上去,

Let Provider = Moyaprovider (endpointclosure:publicparamendpointclosure)

(iii) monitoring network status via plug-in mode

Usually we do some state-of-the-loading when we make a request for the network, so you can do it in the form of plugins. Moya has 4 plugins by default:

    • Accesstokenplugin Management Accesstoken Plug-in
    • Credentialsplugin Management Certified Plug-in
    • Networkactivityplugin plug-ins for managing network status
    • Networkloggerplugin Management Network Log plug-in

Here is a demonstration of the use of Networkactivityplugin:

inch            Switch type {            case  . Began:                NSLog (" show loading")              Case . Ended:                NSLog (" Hide loading")            }        }

Also in the creation of the requestedProvider把它添加上去即可

Let Provider = moyaprovider<accountservice> (plugins: [Networkplugin])

Of course you can also customize some of the functions of the plug-in, only need to implement the Plugintype protocol, specific features can refer to the Moya default plugin:

class Customplugin:plugintype {        //  mark:plugin}

(d) Setting the time-out for the interface

General network requests need to be based on the specific business interface to set the appropriate time-out, you can refer to the method to set up,

in Elsereturn  }                        //Set request time-out                              Done             (. Success (Request))        }

Also in the creation of Provider把它添加上去即可 the requested

Let Provider = moyaprovider<accountservice> (requestclosure:requesttimeoutclosure)

At this point, the use of Moya for the basic usage of the network request has been introduced, the main record is just a pharmacy, of course, also hope to have a little use for everyone, thank you!

Data reference:

Http://www.jianshu.com/p/38fbc22a1e2b

Https://github.com/Moya/Moya

Swift Network request (MOYA)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.