IOS开发和Web开发一样,网络请求方式包括Get和Post方式。Get和Post两者有和特点和区别,在本篇博客中不做过多的论述,本篇的重点在于如何GET数据和POST数据。下面还会提到如何在我们的项目中使用CocoaPods, CocoaPods的安装和使用教程请参考链接http://code4app.com/article/cocoapods-install-usage。上面详细的介绍了CocoaPods的安装过程和如何通过CocoaPods引入第三方类库。在本篇博客中提到CocoaPods,是因为我们需要用CocoaPods来引入AFNetWorking,然后在网络请求中使用AFNetWorking来实现我们图片的提交。
下面用的API是由新浪微博提供的官方API,链接地址:http://open.weibo.com/wiki/微博API, 想使用新浪微博的API首先得注册成开发者获取一个和自己新浪微博绑定的access_token,我们可以通过这个令牌来使用新浪微博提供的API.
1.Get方式的请求
(1)下面会使用公共服务的国家,省份,和城市的接口,来学习一下GET请求方式
(2)我们要完成什么要的任务呢?少说点吧,上几张图最为直接
(3)上面的数据是通过API获取的,获取完后再显示在我们的tableView中,将会提供一些关键的实现代码,准备工作是新建三个TabelViewController然后配置相应的cell。下面就以第一个TableView为例,因为后两个和第一个差不多,所以就不做赘述,下面是网路请求的关键代码:
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 |
//网络请求用的API NSString *urlString = @"https://api.weibo.com/2/common/get_country.json?access_token=你自己的access_token"; //把urlString转换成url NSURL *url = [NSURL URLWithString:urlString]; //创建URL请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //copy_self在Block中使用,避免强引用循环 __weak __block ChinaTableViewController *copy_self = self; //执行请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //连接失败时 if (connectionError) { NSLog(@"%@", [connectionError localizedDescription]); return ; } NSError *error = nil; //把json转换成数组 copy_self.dataSource = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; //转换失败 if (error) { 29 NSLog(@"%@", [error localizedDescription]); return; } //tableView的重载 [copy_self.tableView reloadData]; }]; |
代码说明:
1.创建要请求的API,根据你要获取的数据参考API来拼接你要的URL.
2.根据拼接的URL来创建URL请求对象;
3.发送请求,上面用的是异步请求方式,同步请求会阻塞线程。
4.在block回调中把返回的JSON解析成数组并加载到我们的表示图
(4).把数据显示在表视图上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dataSource.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; NSString *key = [NSString stringWithFormat:@"%03d",indexPath.row+1]; cell.textLabel.text = self.dataSource[indexPath.row][key]; return cell; } |
(5)因为在下一个页面要请求数据的时候得用到第一个页面的数据,也就是在请求省份的时候得知道国家的编码,所以要把国家的编码传到第二个页面中,第三个页面和第二个页面也是类似。下面是通过KVC传值的代码