異步請求使用與同步和隊列式異步請求相同的對象,只不過又增加了另一個對象,即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