您好,登录后才能下订单哦!
上篇博客提到同步请求,同步请求用户体验不好,并且介绍了在同步方法上实现异步,事实上iOS SDK也提供了异步请求的方法。异步请求会使用NSURLConnection委托协议NSURLConnectionDelegate。在请求不同阶段 会回调委托对象方法。NSURLConnectionDelegate协议的方法有:
connection:didReceiveData: 请求成功,开始接收数据,如果数据量很多,它会被多次调用;
connection:didFailWithError: 加载数据出现异常;
connectionDidFinishLoading: 成功完成加载数据,在connection:didReceiveData方法之后执行;
使用异步请求的主视图控制器MasterViewController.h代码如下:
- #import <UIKit/UIKit.h>
 - #import “NSString+URLEncoding.h”
 - #import “NSNumber+Message.h”
 - @interface MasterViewController : UITableViewController <NSURLConnectionDelegate>
 - @property (strong, nonatomic) DetailViewController *detailViewController;
 - //保存数据列表
 - @property (nonatomic,strong) NSMutableArray* listData;
 - //接收从服务器返回数据。
 - @property (strong,nonatomic) NSMutableData *datas;
 - //重新加载表视图
 - -(void)reloadView:(NSDictionary*)res;
 - //开始请求Web Service
 - -(void)startRequest;
 - @end
 
上 面的代码在MasterViewController定义中实现了NSURLConnectionDelegate协议。datas属性用来存放从服务器 返回的数据,定义为可变类型,是为了从服务器加载数据过程中不断地追加到这个datas中。MasterViewController.m代码如下:
- /*
 - * 开始请求Web Service
 - */
 - -(void)startRequest {
 - NSString *strURL = [[NSString alloc] initWithFormat:
 - @”http://iosbook3/mynotes/webservice.php?email=%@&type=%@&action=%@”,
 - @”<你的iosbook1.com用户邮箱>”,@”JSON”,@”query”];
 - NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
 - NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
 - NSURLConnection *connection = [[NSURLConnection alloc]
 - initWithRequest:request
 - delegate:self];
 - if (connection) {
 - _datas = [NSMutableData new];
 - }
 - }
 - #pragma mark- NSURLConnection 回调方法
 - - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { ①
 - [_datas appendData:data];
 - }
 - -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {
 - NSLog(@”%@”,[error localizedDescription]);
 - }
 - - (void) connectionDidFinishLoading: (NSURLConnection*) connection { ②
 - NSLog(@”请求完成…”);
 - NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:_datas
 - options:NSJSONReadingAllowFragments error:nil];
 - [self reloadView:dict];
 - }
 
在 第①行的connection:didReceiveData:方法中,通过[_datas appendData:data]语句不断地接收服务器端返回的数据,理解这一点是非常重要的。如果加载成功就回调第②行的 connectionDidFinishLoading:方法,这个方法被回调也意味着这次请求的结束,这时候_datas中的数据是完整的,在这里把数 据发送回表示层的视图控制器。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。