iOS-渐进式加载图片

import

/**
 渐进式加载图片
 */
- (void)advanceLoadImage {
    
    _incrementallyImgSource = CGImageSourceCreateIncremental(NULL);
    _recieveData = [[NSMutableData alloc] init];

    
    
    resultView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 300)];
    [self.view addSubview:resultView];
    
    
    NSURL *url=[NSURL URLWithString:@"http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1207/05/c0/12233333_1341470829710.jpg"];
    //NSURL *url=[NSURL URLWithString:@"http://h6.86.cc/walls/20150721/1440x900_5d8830739233940.jpg"];

    NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    [task resume];
    
    

}


// 1.接收到服务器的响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    // 允许处理服务器的响应,才会继续接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
    
    _expectedLeght = response.expectedContentLength;
    NSLog(@"_expectedLeght   %lld",_expectedLeght);
    
}

// 2.接收到服务器的数据(可能调用多次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        
        [_recieveData appendBytes:bytes length:byteRange.length];
        
        //此处为测试,使用上面的方法会导致内存激增,所以 为了内存考虑使用 NSFileHandle ,将数据流保存到本地,需要时再从 NSFileHandle 中读取data 进行操作
    }];
    
    BOOL isloadFinish = NO;
    if (_expectedLeght == _recieveData.length) {
        isloadFinish = YES;
    }
    
    CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, isloadFinish);
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
    UIImage *imageaa = [UIImage imageWithCGImage:imageRef];
    resultView.image=imageaa;
    CGImageRelease(imageRef);
    
    NSLog(@"_recieveData  %lu",(unsigned long)_recieveData.length);
    
}


// 3.请求成功或者失败(如果失败,error有值)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    // 请求完成,成功或者失败的处理
}


你可能感兴趣的:(iOS-渐进式加载图片)