码迷,mamicode.com
首页 > 移动开发 > 详细

IOS ---网络异步请求

时间:2015-04-30 16:09:31      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:ios   网络   异步请求   

异步请求使用与同步和队列式异步请求相同的对象,只不过又增加了另一个对象,即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

IOS ---网络异步请求

标签:ios   网络   异步请求   

原文地址:http://blog.csdn.net/lf644206005/article/details/45395773

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!