你好,游客 登录
背景:
阅读新闻

iOS开发那些事-iOS网络编程异步GET方法请求编程 - tony_关东升

[日期:2013-03-27] 来源:  作者: [字体: ]

上篇博客提到同步请求,同步请求用户体验不好,并且介绍了在同步方法上实现异步,事实上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中的数据是完整的,在这里把数据发送回表示层的视图控制器。






收藏 推荐 打印 | 录入:admin | 阅读:
相关新闻