数据下载-block 形式的异步请求

这里给大家写了一个方法 ,我们使用block 进行数据异步下载 
//block 形式的异步请求
-(void)asyncDownloadWithBlock{
    //菊花
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //将字符串转化成URL 地址
    NSURL *url = [NSURL URLWithString:self.myURLStr];
    
    //创建一个对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //获取主队列
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    
    NSLog(@"current:%@",[NSThread currentThread]);
    NSLog(@"isMulti:%d",[NSThread isMultiThreaded]);
    NSLog(@"开始下载");
    [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"block 回调,下载完成");
        NSLog(@"current:%@",[NSThread currentThread]);
        NSLog(@"%d",[NSThread isMultiThreaded]);
        
        //取消菊花
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        NSLog(@"%@",response);
        NSHTTPURLResponse *httpRespone = (NSHTTPURLResponse *)response;
        
        //状态码
        if (httpRespone.statusCode != 200) {
            NSLog(@"下载出错");
            
        }
        if (data && !connectionError) {//这里注意判断 数据存在且 连接没有错误
            self.imageView.image = [UIImage imageWithData:data];
            
        }
        else{
            NSLog(@"下载出错");
        }
        
    }];
    NSLog(@"current:%@",[NSThread currentThread]);
    NSLog(@"isMulti:%d",[NSThread isMultiThreaded]);
    NSLog(@"************");
    
}

你可能感兴趣的:(对象,异步,下载,ios开发,block)