//1. NSData dataWithContentsOfURL // [self.icon setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:tempUrl]]]; //2. dispath形式添加到異步處理 // [self imageDownLoadByUrlASYNC:tempUrl Complete:^(UIImage *image) { // [self.icon setImage:image]; // }]; //3. 當前我所選用的方式 邊下載邊加載的方式 用的CGImageRef imageWithCGImage _request = [[NSURLRequest alloc] initWithURL:tempUrl]; _conn = [[NSURLConnection alloc] initWithRequest:_request delegate:self]; _incrementallyImgSource = CGImageSourceCreateIncremental(NULL); _recieveData = [[NSMutableData alloc] init]; _isLoadFinished = false; self.icon.alpha = .5; self.lblTitle.alpha = .5; [self.lblTitle setText:appName];
第一種方式,是基本上很少有人用的 是最基礎的方式 這種方式有個問題 就是網絡不好的情況下會卡主線程,導致程序假死
第二種方式,請款這段實現代碼
// //-(void)imageDownLoadByUrlASYNC:(NSURL *)url Complete:(complete)finished //{ // //異步並列執行 // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // UIImage *image = nil; // NSError *error; // NSData *responseData = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&error]; // image = [UIImage imageWithData:responseData]; // //跳回主隊列執行 // dispatch_async(dispatch_get_main_queue(), ^{ // //在主隊列中進行ui操作 // finished(image); // }); // // }); //}雖然情況跟第一種實現一樣,但是將執行代碼添加到對應的異步執行中 然後再成功下載之後 獲取到image之後 放到主線程執行回調 設置image
第三種方式 需要以下代碼 這是我百度到的方式
#pragma mark -- NSURLConnectionDataDelegate -(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response { _expectedLeght=response.expectedContentLength; NSLog(@"expectedLength:%lld",_expectedLeght); NSString*mimeType=response.MIMEType; NSLog(@"MIMETYPE%@",mimeType); NSArray*arr=[mimeType componentsSeparatedByString:@"/"]; if(arr.count<1||![[arr objectAtIndex:0] isEqual:@"image"]) { NSLog(@"notaimageurl"); [connection cancel]; _conn=nil; } } -(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error { NSLog(@"Connection%@error,errorinfo:%@",connection,error); } -(void)connectionDidFinishLoading:(NSURLConnection*)connection { NSLog(@"ConnectionLoadingFinished!!!"); //ifdownloadimagedatanotcomplete,createfinalimage if(!_isLoadFinished){ CGImageSourceUpdateData(_incrementallyImgSource,(CFDataRef)_recieveData,_isLoadFinished); CGImageRef imageRef=CGImageSourceCreateImageAtIndex(_incrementallyImgSource,0,NULL); UIImage * image=[UIImage imageWithCGImage:imageRef]; [self.icon setImage:image]; CGImageRelease(imageRef); } } -(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); UIImage * image=[UIImage imageWithCGImage:imageRef]; [self.icon setImage:image]; CGImageRelease(imageRef); }