NSURLConnection的3种请求方式

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic,copy)NSString *myUrlStr;

//接收数据用的data
@property (nonatomic,strong)NSMutableData *result;
//记录数据的总大小
@property (nonatomic,assign)float totalSize;

@end

@implementation ViewController
/*
 Connection
 1.同步请求:一般不怎么用
 2.异步请求:block方式
 3.异步请求:代理模式

 */
-(NSMutableData *)result
{
    if (!_result)
    {
        _result = [NSMutableData new];
    }
    return _result;
}
- (IBAction)btnDownLoad:(UIButton *)sender
{
//    [self syncDownloadWithConnection];
//    [self asyncDownloadWithConnectionBlock];
    [self asyncDownloadWithConnectionDelegate];
}

#pragma mark -同步-
-(void)syncDownloadWithConnection
{
    //1.将字符串地址转换成URL
    NSURL *url = [NSURL URLWithString:_myUrlStr];
    //2.将URL封装成NSURLRequest对象,可悲Connection使用
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.connection建立网络连接
    //给出所需的参数
    NSURLResponse *response;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        NSLog(@"%@",error);
        return;
    }

    UIImage *image = [UIImage imageWithData:data];
    self.imageView.image = image;

}

#pragma mark -异步-
//代理模式
-(void)asyncDownloadWithConnectionDelegate
{
    //1.将字符串地址转换成URL
    NSURL *url = [NSURL URLWithString:_myUrlStr];
    //2.将URL封装成NSURLRequest对象,可被Connection使用
    //NSURLRequestReloadIgnoringLocalCacheData 忽略本地缓存
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    //3.代理方法,异步请求数据
    [NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark -NSURLConnectionDataDelegate-
//调用它就证明,连接有响应,已经下载完相应头,开始下载
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.progressView.hidden = NO;
    //expectedContentLength 获取数据的总长度
    self.totalSize = response.expectedContentLength;
    self.result.length = 0;
}
//调用它就证明,正在接收数据,响应体,根据数据的大小,会不间断的接收,直至全部完成
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //不间断接收数据
    [self.result appendData:data];
    //获取进度比
    float pv = self.result.length / self.totalSize;
    //刷新进度(当前就是主线程,可以不去获取,如果不清楚,最好获取主线程去刷新UI)
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressView.progress = pv;
    });

}
//调用它就证明下载完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageView.image = [UIImage imageWithData:self.result];
    });
}
//连接发生错误,下载失败(1.断网 2.网址错误)
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@“%@“,error);
}

//block模式
-(void)asyncDownloadWithConnectionBlock
{
    //显示加载圈
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    //1.将字符串地址转换成URL
    NSURL *url = [NSURL URLWithString:_myUrlStr];
    //2.将URL封装成NSURLRequest对象,可悲Connection使用
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"开始请求");
    //3.异步请求(block形式,iOS5.0之后推出的方法)
    //给出相关参数queue
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError)
    {
        NSLog(@"block返回");
        NSLog(@"%@",[NSThread currentThread]);
        NSLog(@"响应:%@",response);
        /*
        //第一种判断方式
        if (!connectionError && data)
        {
            UIImage *image = [UIImage imageWithData:data];
            self.imageView.image = image;
        }*/
        //第二种判断方式
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
       if(httpResponse.statusCode == 200)
       {
           UIImage *image = [UIImage imageWithData:data];
           self.imageView.image = image;

       }
        //关闭加载圈
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        /*
            block优点:方便使用,比如json请求
            缺点:整体返回,不能分布接收,不能显示进度
        */
    }];
    NSLog(@"下载完成");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _myUrlStr = @"http://pic18.nipic.com/20111130/8885119_125321390000_2.jpg";
    self.progressView.hidden = YES;
}
@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值