IOS SWIFT Network Request JSON parsing basics One

Source: Internet
Author: User

In the era of mobile internet, network communication is an essential function of mobile phone. Network communication is also essential in the application to enhance client-server interaction. Use Nsurlconnection to implement HTTP communication. Nsurlconnection provides both asynchronous request and synchronous request communication methods. Synchronizing request data can cause the main thread to block, and is usually not recommended when large data is requested or the network is not smooth.

The steps to establish communication are the same regardless of the synchronization request or the asynchronous request:

1 Creating Nsurl

2 Creating Nsurlrequest

3 Creating Nsurlconnection

When Nsurlconnection is created successfully, an HTTP connection is created. The difference between an asynchronous request and a synchronous request is that an asynchronous request is created, the user can do other things, the request is executed by another thread, and the communication results and procedures are executed in the callback function. Synchronization requests are different and require the end user to be requested to do other things.

Import Uikitclass Viewcontroller:uiviewcontroller,nsurlconnectiondatadelegate {var jsondata = NSMutableData () over Ride func viewdidload () {super.viewdidload ()//Do any additional setup after loading the view, typically F                Rom a nib.        Synchronousrequest ()//asynchronousrequest ()}//Sync request func synchronousrequest (), Void { Create the required nsurl var url:nsurl! = Nsurl (string: "http://m.weather.com.cn/mweather/101010100.html")//Create request Object var = nsurlrequest (URL:        URL)//define Response object Var response:nsurlresponse?        Define the Error object var error:nserror? Make a request var data = Nsurlconnection.sendsynchronousrequest (Request, Returningresponse: &response, Error: &err OR) if (Error! = nil) {//Handling error println (error?. Code) println (error?). Description)} else {var josnstring = NSString (data:data!, Encoding:nsutf8stringencoding)//Convert to String println (josnstring)}}//Asynchronous request Func Asynchronousrequest ()- > Void {//create required nsurl var url:nsurl! = Nsurl (string: "Http://m.weather.com.cn/mweather/101010100.html" )//Create request object var requests = Nsurlrequest (Url:url)//create connection var connection = nsurlconnection (reques T:request, delegate:self)//temporary understanding is not thorough, to be in-depth understanding connection? Scheduleinrunloop (Nsrunloop.currentrunloop (), formode:nsrunloopcommonmodes)//start connection?. Start ()}//will send request Func connection (connection:nsurlconnection, Willsendrequest request:nsurlrequest, Redire Ctresponse response:nsurlresponse?) Nsurlrequest? {return request}//Receive response func connection (connection:nsurlconnection, Didreceiveresponse Response:ns        Urlresponse) {}//Received data func connection (connection:nsurlconnection, Didreceivedata data:nsdata) { Self.jsonData.appendData (DATA)}//requires a new content stream func connection (connection:nsurlconnection, Neednewbodystream request:nsurlrequest), N Sinputstream? {return request.} Httpbodystream}//Send data request func connection (connection:nsurlconnection, Didsendbodydata byteswritten:int, tot Albyteswritten:int, Totalbytesexpectedtowrite:int) {}//Cache response Func Connection (connection:nsurlconn Ection, Willcacheresponse cachedresponse:nscachedurlresponse), Nscachedurlresponse?        {return Cachedresponse}//Request end Func connectiondidfinishloading (connection:nsurlconnection) { Result of the request var jsonstring = NSString (Data:self.jsonData, encoding:nsutf8stringencoding)//Convert to String//p RINTLN (jsonstring)//parsing JSON let Dict:anyobject?                = Nsjsonserialization.jsonobjectwithdata (Self.jsondata, options:NSJSONReadingOptions.AllowFragments, Error:nil) var dic = Dict as! Nsdictionary Let Weatherinfo = Dic.objectforkey ("Weatherinfo") as! nsdictionary Let city = Weatherinfo.objectforkey ("City") as! String Let date_y = Weatherinfo.objectforkey ("date_y") as! String Let Temp1 = Weatherinfo.objectforkey ("Temp1") as! String} override func didreceivememorywarning () {super.didreceivememorywarning ()//Dispose            of any resources the can be recreated. }}

IOS SWIFT Network Request JSON parsing basics One

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.