iOS Swift builds its own HTTP request tool

Source: Internet
Author: User

In the development of iOS, network requests can not be less, when it comes to the network request may use the most is the third party than people more famous afnetworking, Alamofire, etc., the original use of less. Use the native method provided by iOS today to build your own Web request tool. The great God's path to growth is now set sail.

The first step: first build a class such as Http is called as follows:

Defining Request Types

Enum HttpMethod {

Case GET,

POST

}

Define class methods in HTTP to make requests for ease of use

Class Http {

class Func request (Method:httpmethod, Url:string,params:[string:any]=[:],complete: @escaping (_result:string), Void,error: @escaping (_error:error?) ->void) {

var url = URL

Processing parameters in order to facilitate the extraction of a method here to handle the parameters

Let Param =self.parserparams (params:params)

Set the GET Request parameters

Ifmethod = =. Get&&param! = "" {

Url.append ("? \ (param)")

}

Let_url =url (string:url)!

Let request =nsmutableurlrequest (URL: _url)

Setting the time-out period

Request.timeoutinterval=50

Set Request mode

request.httpmethod= method = =. GET? " GET ":" POST "

Set POST request parameters

If method = =. post&& param! = "" {

Request.httpbody=param.data (using:. UTF8)

}

Let session =urlsession.shared

Let Httptask = Session.datatask (with:request as URLRequest) {(Data,response, err) in

Callback in the main thread facilitates processing of data logic in the interface

OperationQueue.main.addOperation {

If Err!=nil{

Error callback

Error (ERR)

Return

}

The request succeeded in returning the result

Complete (String (data:data!, Encoding:String.Encoding.utf8)!)

}

}

Start a task

Httptask.resume ()

}

Converting a dictionary into a parameter string for a network request

Private class Func Parserparams (Params:[string:any])->string{

var newstr= ""

For Param in params{

Newstr.append ("\ (Param.key) =\ (param.value) &")

}

Return NEWSTR

}

}

The second step starts the test: called in Viewcontroller,

Class viewcontroller:uiviewcontroller{

Override Func Viewdidload () {

Super.viewdidload ()

Let URL = "http://api.budejie.com/api/api_open.php"

Http.request (method:. GET, Url:url, params: ["a": "List", "C": "Data", "type": 1], complete: {R in

Print ("Request Result:", R)

}, Error:{error in

Print ("Request error:", error.debugdescription)

})

So this simple HTTP request tool is written, isn't it simple? If you think you can remember to follow me oh, if you have any questions welcome message!

Jane Book Address: Code Life Welcome attention

iOS Swift builds its own HTTP request tool

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.