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
30
31
32
33
|
import
UIKit
//自定义http协议
protocol
HttpProtocol
{
//定义一个方法接收一个字典
func
didRecieveResults(resultes:
NSDictionary
)
}
class
HttpController
:
NSObject
{
//定义一个可选代理
var
delegate:
?
onSearch(url:
@H_404_158@String
){
//定义一个NSURL
let
nsUrl:
NSURL
=
(string: url)!
//定义一个NSURLRequest
request:
NSURLRequest
(
URL
: nsUrl)
//异步获取数据
NSURLConnection
.sendAsynchronousRequest(request,
queue:
NSOperationQueue
.mainQueue(),
completionHandler: {(response:
NSURLResponse
?,data:
NSData
NSError
?)
->
@H_404_158@Void
in
//由于我们获取的数据是json格式,所以我们可以将其转化为字典。
jsonResult:
=try!
NSJSONSerialization
.
JSONObjectWithData
(
data!,
options:
NSJSONReadingOptions
MutableContainers
)
as
!
NSDictionary
//将数据传回给代理
self
.delegate?.didRecieveResults(jsonResult)
})
}
}
|
ViewController
UIViewController
,
{
//获取网络数据的类
eHttp:
()
//接收频道列表的数组
channelData:
NSArray
()
override
viewDidLoad() {
super
.viewDidLoad()
//为HttpController实例设置代理
eHttp.delegate=
self
//获取频道数据
eHttp.onSearch(
"http://www.douban.com/j/app/radio/channels"
)
}
//实现HttpProtocol协议的方法
didRecieveResults(results:
){
if
(results[
"channels"
] !=
nil
){
//如果channels关键字的value不为nil,获取的就是频道数据
.channelData=results[
]
NSArray
}
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
|
3,请求数据样例
{
"channels"
: [
"abbr_en"
"My"
"name"
"私人兆赫"
"channel_id"
: 0
},
{
"华语"
""
"1"
""
{
"欧美"
: 1,
"2"
""
}
]
}
|