加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift语言IOS8开发战记24 解析Json

发布时间:2020-12-14 04:24:35 所属栏目:百科 来源:网络整理
导读:在IOS中使用NSURLConnection实现http通信,NSURLConnection提供了异步和同步两种通信方式,同步请求会造成进程阻塞,通常我们使用异步的方式,不管同步还是异步,建立通信的基本步骤都是一样的: 1,创建NSURL 2,创建Request对象 3,创建NSURLConnection连

在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 UIKit

class 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 UIKit

class 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)
    }

运行,同样得到结果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读