同步请求的用户体验不是很好,因此很多情况下我们会采用异步调用。iOS SDK也提供了异步请求的方法,
而异步请求会 使用NSURLConnection委托协议NSURLConnectionDelegate。在请求的不同阶段,会回调委托
对象的方法。NSURLConnectionDelegate协议的方法有如下几个。
connection:didReceiveData:。请求成功,建立连接,开始接收数据。如果数据量很多,它会被多次
调用。
connection:didFailWithError:。加载数据出现异常。
MasterViewController.m中的代码如下:
编码stringByAddingPercentEscapesUsingEncoding:
解码stringByReplacingPercentEscapesUsingEncoding:
而异步请求会 使用NSURLConnection委托协议NSURLConnectionDelegate。在请求的不同阶段,会回调委托
对象的方法。NSURLConnectionDelegate协议的方法有如下几个。
connection:didReceiveData:。请求成功,建立连接,开始接收数据。如果数据量很多,它会被多次
调用。
connection:didFailWithError:。加载数据出现异常。
connectionDidFinishLoading:。成功完成数据加载,在connection:didReceiveData方法之后执行。
使用异步请求的主视图控制器为MasterViewController。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.m中的代码如下:
/*
* 开始请求Web Service
*/
-(void)startRequest {
NSString *strURL = [[NSString alloc]initWithFormat:@"http://iosbook1.com/service/mynotes/webservice.php?email=%@&type=%@&action=%@",
@"<你的iosbook1.com用户邮箱>",@"JSON",@"query"];
//使用了NSNumber+Message.h分类 方法对url编码
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]语句不断地接收服务器端返回的数据
[_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];
}
在请求完成时调用,用于重新加载表视图中的数据。reloadView:方法的代码如下:
//重新加载表视图
-(void)reloadView:(NSDictionary*)res
{
NSNumber *resultCodeObj = [res objectForKey:@"ResultCode"];
if ([resultCodeObj integerValue] >=0)
{
self.listData = [res objectForKey:@"Record"];
[self.tableView reloadData];
} else {
NSString *errorStr = [resultCodeObj errorMessage]; ①
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息"
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
}
Foundation 框架也提供了基于Objective-C 进行URL 编码和解码的方法:
编码stringByAddingPercentEscapesUsingEncoding:
解码stringByReplacingPercentEscapesUsingEncoding: