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

在IOS中使用NSURLConnection实现http通信,NSURLConnection提供了异步和同步两种通信方式,同步请求会造成进程阻塞,通常我们使用异步的方式,,不管同步还是异步,建立通信的基本步骤都是一样的:

1,创建NSURL

2,创建Request对象

3,创建NSURLConnection连接

第3步结束后就建立了一个http连接。

这里我们用一个开放的api做例子:

这是北京市的当前天气信息的json,我们首先来写一个同步的网络连接来获取这个json,新建一个工程,在页面上添加一个按钮,每次点击按钮就会输出json的内容到控制台,控制器代码:

import UIKitclass ViewController: UIViewController {@IBAction func showWeatherJson(sender: UIButton) {//创建urlvar url:NSURL! = NSURL(string: "")//创建请求对象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: "")//创建请求对象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

相关文章:

你感兴趣的文章:

标签云: