Swift Language IOS8 Development War 24 parsing JSON

Source: Internet
Author: User

Using Nsurlconnection for HTTP communication in iOS, Nsurlconnection provides both asynchronous and synchronous communication methods, which can cause process blocking, usually in the same way that we use async, whether synchronous or asynchronous, and the basic steps for building communication are the same:

1, create Nsurl

2, create the Request object

3, create a nsurlconnection connection

An HTTP connection is established at the end of the 3rd step.

Here we use an open API to do an example:

Http://www.weather.com.cn/adat/sk/101010100.html

This is the current weather information in Beijing JSON, we first write a synchronous network connection to get this JSON, a new project, add a button on the page, each click of the button will output the JSON content to the console, controller code:

Import Uikitclass Viewcontroller:uiviewcontroller {    @IBAction func Showweatherjson (Sender:uibutton) {        // Create URL        var url:nsurl! = Nsurl (string: "http://www.weather.com.cn/adat/sk/101010100.html")       //Create Request object        var Urlrequest:nsurlrequest = Nsurlrequest (url:url)        //Create Response object        var response:nsurlresponse?        Create Error Object        var error:nserror?        Make a request        var data:nsdata? = Nsurlconnection.sendsynchronousrequest (URLRequest, Returningresponse: &response, Error: &error)        if error! = Nil        {        println (error?. Code)        println (error?). Description)                } else {        var jsonstring = NSString (data:data!, encoding:nsutf8stringencoding)            println ( jsonstring)}}}            

The results of the operation are as follows:



The following shows the code for the asynchronous request:

Import Uikitclass viewcontroller:uiviewcontroller,nsurlconnectiondatadelegate,nsurlconnectiondelegate {       @ ibaction func Getweatherjson (Sender:uibutton) {                //Create Nsurl object        var url:nsurl! = Nsurl (string: "/HTTP/ Www.weather.com.cn/adat/sk/101010100.html ")        //Create Request object        var urlrequest:nsurlrequest = nsurlrequest (Url:url)        //Network Connection object        var conn:nsurlconnection? = Nsurlconnection (Request:urlrequest, delegate:self)        conn?. Scheduleinrunloop (Nsrunloop.currentrunloop (), formode:nsrunloopcommonmodes)        //EXECUTE        conn?. Start ()            }}

Then add the code in the proxy method, Agent Nsurlconnectiondatadelegate's proxy method is as follows:

    Func connection (connection:nsurlconnection, Willsendrequest request:nsurlrequest, Redirectresponse response:nsurlre Sponse?) Nsurlrequest? {//The request will be sent to return requests} Func connection (connection:nsurlconnection, didreceiveresponse response:        Nsurlresponse) {//Receive response} Func connection (connection:nsurlconnection, Didreceivedata data:nsdata) { Data received} Func connection (connection:nsurlconnection, Neednewbodystream request:nsurlrequest), Nsinputstream? {//requires a new content flow return request. Httpbodystream} func Connection (connection:nsurlconnection, Didsendbodydata byteswritten:int, Totalbyteswritten: Int, Totalbytesexpectedtowrite:int) {//Send data Request} Func connection (Connection:nsurlconnection, WILLCACHERESPO NSE cachedresponse:nscachedurlresponse)-Nscachedurlresponse?        {//Cache response return Cachedresponse} func connectiondidfinishloading (connection:nsurlconnection) { End of request   } 

Define a nsmutabledata type data stream that collects data streams in the Didreceivedata proxy method, with the following code:

var jsondata:nsmutabledata = Nsmutabledata ()    func connection (connection:nsurlconnection, didreceivedata data: NSData) {        //Received Data        Jsondata.appenddata    }

Resolves the jsondata data flow within the agent method that connectiondidfinishloading ends the request. The code is as follows:

Func connectiondidfinishloading (connection:nsurlconnection) {        //request End        var jsonstring = nsstring (data: Jsondata, encoding:nsutf8stringencoding)        println (jsonstring)    }

Run and get the same result:



Swift Language IOS8 Development War 24 parsing JSON

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.