IOS 載入網狀圖片的方式對比
//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);}
這個方法經過我測試了 非常好用 但是不知道會不會有什麼bug 只是剛使用 並且使用者體驗也會相應增加