微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift语言IOS8开发战记24 解析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 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)
    }

运行,同样得到结果:

原文地址:https://www.jb51.cc/swift/326934.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐