使用NSURLConnection.sendAsynchronousRequest()可以采用异步获取的方式取得数据。下面通过对数据获取类进行封装,演示如何进行数据请求与接收。
1,HttpController.swift (数据获取封装类,结果处理协议)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import UIKit //自定义http协议 protocol HttpProtocol { //定义一个方法接收一个字典 func didRecieveResults(resultes: NSDictionary ) } class HttpController : NSObject { //定义一个可选代理 var delegate: HttpProtocol ? //定义一个方法运过来获取网络数据,接收参数为网址 func onSearch(url: String ){ //定义一个NSURL var nsUrl: NSURL = NSURL (string: url)! //定义一个NSURLRequest var request: NSURLRequest = NSURLRequest ( URL : nsUrl) //异步获取数据 NSURLConnection .sendAsynchronousRequest(request, queue: NSOperationQueue .mainQueue(), completionHandler: {(response: NSURLResponse !,data: NSData !,error: NSError !)-> Void in //由于我们获取的数据是json格式,所以我们可以将其转化为字典。 var jsonResult: NSDictionary = NSJSONSerialization . JSONObjectWithData (data, options: NSJSONReadingOptions . MutableContainers , error: nil ) as NSDictionary //将数据传回给代理 self .delegate?.didRecieveResults(jsonResult) }) } } |
2,ViewController.swift (使用样例)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import UIKit class ViewController : UIViewController , HttpProtocol { //获取网络数据的类 var eHttp: HttpController = HttpController () //接收频道列表的数组 var channelData: NSArray = NSArray () override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //为HttpController实例设置代理 eHttp.delegate= self //获取频道数据 } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //实现HttpProtocol协议的方法 func didRecieveResults(results: NSDictionary ){ if (results[ "channels" ] != nil ){ //如果channels关键字的value不为nil,获取的就是频道数据 self .channelData=results[ "channels" ] as NSArray println ( self .channelData[0][ "name" ] as String ) //私人兆赫 } } } |
3,请求数据样例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
{ "channels" : [ { "name_en" : "Personal Radio" , "seq_id" : 0, "abbr_en" : "My" , "name" : "私人兆赫" , "channel_id" : 0 }, { "name" : "华语" , "seq_id" : 0, "abbr_en" : "" , "channel_id" : "1" , "name_en" : "" }, { "name" : "欧美" , "seq_id" : 1, "abbr_en" : "" , "channel_id" : "2" , "name_en" : "" } ] } |