首页 > 代码库 > NSURLConnection类
NSURLConnection类
swift学习--NSURLConnection
先看一下Apple官方文档中对NSURLConnection的描述:
An NSURLConnection object provides support to perform asynchronous loads of a URL request, providing data to a client supplied delegate.
可见USURLConnection可用于从网络进行同步或异步的数据获取。
异步请求数据用到的方法为:
NSURLConnection.sendAsynchronousRequest(NSURLRequest?, queue: NSOperationQueue?, completionHandler: ((NSURLResponse!, NSData!, NSError!) -> Void)?)
同步请求数据用到的方法为:
NSURLConnection.sendsynchronousRequest(NSURLRequest?, queue: NSOperationQueue?, completionHandler: ((NSURLResponse!, NSData!, NSError!) -> Void)?)
应用方法:
比如从豆瓣的API中获取频道列表
//API地址:
var doubanFMChannel = NSURL(String: "http://www.douban.com/j/app/radio/channels")
//URLRequest
var request = NSURLRequest(URL: doubanFMChannel)
//请求频道列表
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response : NSURLResponse!,data:NSData!,error:NSError!) -> Void in
var doubanJsonData = http://www.mamicode.com/NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
self.delegate?.didReceiveResult(doubanJsonData)
}
这里面用到了swift中的闭包。闭包按照我的理解就是一个方法的简写
{(parameter) -> returnType in return statements }
关于NSJSONSerialization.JSONObjectWithData中NSJSONReadingOptions的一点官方文档:
Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary.
Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries.
Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects