话不多说,直接上代码
- (void)viewDidLoad {
[super viewDidLoad];
// _imageURL = [imageURLS retain];
_request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"]];
_conn = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
_incrementallyimgSource = CGImageSourceCreateIncremental(NULL);
_recieveData = [[NSMutableData alloc] init];
_isLoadFinished = false;
view = [[UIImageView alloc] initWithFrame:CGRectMake(10,10, 300, 300)];
view.image = self.image;
[self.view addSubview:view];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
_expectedLeght = response.expectedContentLength;
NSLog(@"expected Length: %lld", _expectedLeght);
NSString *mimeType = response.MIMEType;
NSLog(@"MIME TYPE %@", mimeType);
NSArray * arr = [mimeType componentsSeparatedByString:@"/"];
if (arr.count < 1 || ![[arr objectAtIndex:0] isEqual:@"image"]) {
NSLog(@"not a image url");
[connection cancel];
[_conn release]; _conn = nil;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[_recieveData appendData:data];
_isLoadFinished = false;
if (_expectedLeght == _recieveData.length) {
_isLoadFinished = true;
}
CGImageSourceUpdateData(_incrementallyimgSource, (CFDataRef)_recieveData, _isLoadFinished);
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyimgSource, 0, NULL);
view.image = [UIImage imageWithCGImage:imageRef];
// [self.view addSubview:view];
CGImageRelease(imageRef);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (!_isLoadFinished) {
CGImageSourceUpdateData(_incrementallyimgSource, (CFDataRef)_recieveData, _isLoadFinished);
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyimgSource, 0, NULL);
view.image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
[view setNeedsLayout];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
}