异步GET请求方法

同步请求的用户体验不是很好,因此很多情况下我们会采用异步调用。iOS SDK也提供了异步请求的方法,
而异步请求会 使用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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值