swift語言IOS8開發戰記24 解析Json

來源:互聯網
上載者:User

標籤:ios8   swift   網路通訊   json   非同步通訊   

在IOS中使用NSURLConnection實現http通訊,NSURLConnection提供了非同步和同步兩種通訊方式,同步請求會造成進程阻塞,通常我們使用非同步方式,不管同步還是非同步,建立通訊的基本步驟都是一樣的:

1,建立NSURL

2,建立Request對象

3,建立NSURLConnection串連

第3步結束後就建立了一個http串連。

這裡我們用一個開放的api做例子:

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

這是北京市的當前天氣資訊的json,我們首先來寫一個同步的網路連接來擷取這個json,建立一個工程,在頁面上添加一個按鈕,每次點擊按鈕就會輸出json的內容到控制台,控制器代碼:

import UIKitclass ViewController: UIViewController {    @IBAction func showWeatherJson(sender: UIButton) {        //建立url        var url:NSURL! = NSURL(string: "http://www.weather.com.cn/adat/sk/101010100.html")       //建立請求對象        var urlRequest:NSURLRequest = NSURLRequest(URL: url)        //建立響應對象        var response:NSURLResponse?        //建立錯誤對象        var error:NSError?        //發出請求        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)                }            }}

運行結果如下:



下面來展示非同步請求的代碼:

import UIKitclass ViewController: UIViewController,NSURLConnectionDataDelegate,NSURLConnectionDelegate {       @IBAction func getWeatherJson(sender: UIButton) {                //建立NSURL對象        var url:NSURL! = NSURL(string: "http://www.weather.com.cn/adat/sk/101010100.html")        //建立請求對象        var urlRequest:NSURLRequest = NSURLRequest(URL: url)        //網路連接對象        var conn:NSURLConnection? = NSURLConnection(request: urlRequest, delegate: self)        conn?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)        //執行        conn?.start()            }}

然後在代理方法中添加代碼即可,代理NSURLConnectionDataDelegate的代理方法如下:

    func connection(connection: NSURLConnection, willSendRequest request: NSURLRequest, redirectResponse response: NSURLResponse?) -> NSURLRequest? {        //將要發送請求        return request    }    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {        //接收響應    }    func connection(connection: NSURLConnection, didReceiveData data: NSData) {        //收到資料    }    func connection(connection: NSURLConnection, needNewBodyStream request: NSURLRequest) -> NSInputStream? {        //需要新的內容流        return request.HTTPBodyStream    }    func connection(connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {        //發送資料請求    }    func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse? {        //緩衝響應        return cachedResponse    }    func connectionDidFinishLoading(connection: NSURLConnection) {        //請求結束    }

定義一個NSMutableData類型資料流,在didReceiveData代理方法中收集資料流,代碼如下:

 var jsonData:NSMutableData = NSMutableData()    func connection(connection: NSURLConnection, didReceiveData data: NSData) {        //收到資料        jsonData.appendData(data)    }

在connectionDidFinishLoading結束請求的代理方法內,解析jsonData資料流。代碼如下:

func connectionDidFinishLoading(connection: NSURLConnection) {        //請求結束        var jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)        println(jsonString)    }

運行,同樣得到結果:



swift語言IOS8開發戰記24 解析Json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.