异步请求使用与同步和队列式异步请求相同的对象,只不过又增加了另一个对象,即NSURLConnectionDelegate:
上代码:
#import "ViewController.h"
NSInteger totalDownLoaded = 0;
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [NSURL URLWithString:@"http://www.example.com/test.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start];
}
/*
*如果协议处理器接收到来自服务器的重定向请求,就会调用该方法
*/
-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{
// NSLog(@"All Headers = %@", [(NSHTTPURLResponse *) response allHeaderFields]);
return request;
}
/*
*当协议处理器接收到足够的数据来创建URL响应对象时会调用didReceiveResponse方法。如果在接收到足够的数据来构建对象前出现了错误,
*就不会调用该方法
*/
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"All Headers = %@", [httpResponse allHeaderFields]);
NSLog(@"statusCode = %ld", (long)httpResponse.statusCode);
if (httpResponse.statusCode != 200) {
[connection cancel];
return;
}
}
/*
*当协议处理器接收到部分或全部响应体时会调用该方法。该方法可能不会调用,也可能调用多次,并且调用总是跟在最初的connection:didReceiveResponse之后
*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
totalDownLoaded += [data length];
NSLog(@"%ld", (long)totalDownLoaded);
}
/*
*当连接失败时会调用这个委托方法。该方法可能会在请求处理的任何阶段得到调用
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"netWork connect error");
}
/*
*当整个请求完成加载并且接收到的所有数据都被传递给委托后,就会调用该委托方法
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Finish");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
时间: 2024-11-10 15:09:23