IOS ---网络异步请求

本文详细介绍了如何使用NSURLConnection进行异步网络请求。包括请求的初始化、响应的处理、数据接收及错误处理等关键步骤。同时展示了通过实现NSURLConnectionDelegate的方法来监控请求过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值