Use Nsurlconnection.sendasynchronousrequest () to get the data in an asynchronous way. The following encapsulates the data acquisition class, demonstrating how data is requested and received.
1,httpcontroller.swift (Data acquisition encapsulation class, result processing protocol)
| 1234567891011121314151617181920212223242526272829 |
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 (use sample)
| 1234567891011121314151617181920212223242526272829303132333435 |
import UIKitclass 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 //获取频道数据 eHttp.onSearch("http://www.douban.com/j/app/radio/channels") } 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, sample request data
| 12345678910111213141516171819202122232425 |
{ "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": "" } ]} |
Swift-Asynchronous acquisition of network data encapsulation classes