在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) }
运行,同样得到结果: