码迷,mamicode.com
首页 > 其他好文 > 详细

NSURLConnection类

时间:2014-08-04 14:11:17      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   io   数据   for   cti   ar   

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 = 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

 

NSURLConnection类,布布扣,bubuko.com

NSURLConnection类

标签:des   style   http   io   数据   for   cti   ar   

原文地址:http://www.cnblogs.com/dannyhuang/p/3889885.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!