//定义一个方法来获取网络数据,接受参数为网址
func onSearch(url:
String){
//定义一个NSURL
var nsUrl:
NSURL = NSURL(string: url)!
//定义一个NSURLRequest
var request:
NSURLRequest = NSURLRequest(URL: nsUrl)
//异步获取数据
NSURLConnection.sendAsynchronousRequest(request, queue:
NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!)
-> Void in
//由于我们获取的数据是json格式,所以我们可以将其转化为字典
var jsonResult:
NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:
NSJSONReadingOptions.MutableContainers, error:
nil)
as NSDictionary
//将数据传回给代理
self.delegate?.didReceiveResults(jsonResult)
}
}
时间: 2024-10-23 17:35:26