NSURLConnection探究

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.progressView.hidden = YES;
    
    _progressView = [[YXProgressView alloc] init];
    //    _progressView.frame = CGRectMake(20, 20, 100, 100);
    //    _progressView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_progressView];
}

- (IBAction)buttonAction:(id)sender {
    
    self.urlString = URL_String3;
    // 发送同步请求
    // [self syncDownloadWithConnection];
    
    // 发送异步请求
    //    [self asyncDownloadWithBlock];
    
    // 发送代理形式的请求
    [self syncDownloadWithDelegate];
    
}



#pragma mark - 懒加载
- (NSMutableData *)result {
    if (_result == nil) {
        _result = [NSMutableData data];
    }
    return _result;
}

#pragma mark - NSURLConnection  同步请求
/**
 *  同步请求
 */
- (void)syncDownloadWithConnection {
    
    // 1. 创建url 将字符串类型的地址封装为url
    NSURL *url = [NSURL URLWithString:self.urlString];
    
    // 2. 创建请求 将url再次封装为一个NSURLRequest对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 创建响应 NSURLResponse 对象
    NSURLResponse *response;
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    if (error) {
        NSLog(@"请求失败:%@",nil);
        return;
    } else {
        // 数据解析
        //        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        self.imageView.image = [UIImage imageWithData:data];
        //        NSLog(@"dict : %@",dict);
        
    }
}

#pragma mark - NSURLConnection 异步请求 -block
/**
 *  异步请求  整体返回数据,不能分布接收
 */
- (void)asyncDownloadWithBlock {
    
    // 网络状态
    
    // 显示网络状态菊花
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    // 1. 创建url 将字符串类型的地址封装为url
    NSURL *url = [NSURL URLWithString:self.urlString];
    
    // 2. 创建请求 将url再次封装为一个NSURLRequest对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 获取主队列
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    
    // block形式的异步请求5.0之后出现的
    
    NSLog(@"开始下载");
    [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"___block回调,下载完成");
        
        
        // 强制转为HTTP类型的响应,来使用状态码
        // 1. 判断有无数据或者请求成没成功  方式1
        NSHTTPURLResponse *httpResponse  = (NSHTTPURLResponse *)response;
        NSLog(@"%@",httpResponse);
        //        方式1
        //         有数据并且无错
        if (data && connectionError == nil) {
        }
        
        //         == 200 就说明请求成功
        if (httpResponse.statusCode == 200) {
            
            self.imageView.image = [UIImage imageWithData:data];
        } else {
            
            NSLog(@"下载出错");
            
        }
        
    }];
    
    
    NSLog(@"结束下载");
    
    
}

#pragma mark - NSURLConnection  代理
/**
 *  同步请求
 */
- (void)syncDownloadWithDelegate {
    
    NSURL *url = [NSURL URLWithString:self.urlString];
    //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 忽略缓存 设置请求的缓存策略  如果超过10秒终没有响应本次请求就不会执行,
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    // 代理方法异步下载,当调用这个方法的时候,会自动发送异步请求,代理方法是在主线程中执行的。
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
}

// 调用它 就证明已经响应,而且已经下载完响应头 开始下载
// 这个方法只会在已经响应的时候执行一次,然后返回响应头 response
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    /* 响应头里面的内容
    <NSHTTPURLResponse: 0x7f8ab0e1f8d0> { 
     URL: http://img15.3lian.com/2015/f2/52/d/45.jpg } { status code: 200, headers {
        "Accept-Ranges" = bytes;  - > bytes:表示接受,none:表示不接受
        "Content-Length" = 249271;
        "Content-Type" = "image/jpeg";
        Date = "Sat, 29 Aug 2015 14:20:21 GMT";
        Etag = "\"12d66111d73ad01:0\"";
        "Last-Modified" = "Wed, 28 Jan 2015 08:47:37 GMT";
        Server = "Microsoft-IIS/8.5";
    }
     */
    
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //    self.progressView.hidden = NO;
    
    // 获取总长度 The expected length of the response’s content. (read-only)
    self.totalSize = response.expectedContentLength;
    
    NSLog(@"response : \n%@",response);
    
}

// 调用它 就证明正在接收数据,响应体,真正的响应数据,根据数据的大小反复不间断的接收
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSLog(@"%@",[NSThread currentThread]);
    
    [self.result appendData:data];
    CGFloat value = self.result.length/self.totalSize;
    //    self.progressView.progress = value;
    [_progressView setProgress:value];
    NSLog(@"%s",__func__);
}

// 调用它 就证明已经下载完毕,
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //    self.progressView.hidden = YES;
    self.imageView.image = [UIImage imageWithData:self.result];
    NSLog(@"%s",__func__);
    
}

// 调用它 就证明链接发生错误 下载失败
// 1. 断网了
// 2. 网址出错
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    // 关闭状态菊花
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    // 隐藏进度条
    self.progressView.hidden = YES;
    NSLog(@"%s",__func__);
}
- (void)setProgress:(CGFloat)progress {
    
    _progress = progress;
    NSLog(@"progress - %f",progress);
    
    self.label.text = [NSString stringWithFormat:@"%.2f%%",progress * 100];
    
    // 重绘视图的时候调用
    // 在View上做一个重绘的标记,当下一次屏幕刷新的时候就会调用
    [self setNeedsDisplay];
}

/**重绘操作仍然在drawRect方法中完成,但是苹果不建议直接调用drawRect方法,
 当然如果你强制直接调用此方法,当然是没有效果的
 
 苹果要求我们调用UIView类中的setNeedsDisplay方法,
 则程序会自动调用drawRect方法进行重绘。(调用setNeedsDisplay会自动调用drawRect)*/

// 当视图显示的时候会调用,默认只会调用一次
- (void)drawRect:(CGRect)rect {
    
    
    // 1.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 2.拼接路径
    // 圆的中心 在当前的坐标系统指定圆心位置
    CGPoint center = CGPointMake(50, 50);
    // 画圆 圆的八景
    CGFloat radius = 50;
    // 画圆的起点在最右侧 - 90 度即最顶端
    CGFloat startA = -M_PI_2;
    CGFloat endA = -M_PI_2 + _progress * M_PI * 2;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center
                                                        radius:radius
                                                    startAngle:startA
                                                      endAngle:endA
                                                     clockwise:YES];
    
    CGContextAddPath(ctx, path.CGPath);
    
    CGContextStrokePath(ctx);
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值