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&¶m! = "" {
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