2012-11-22 38 views
0

正在爲iphone開發一個rss feed應用程序,因爲我有一個tableview,當用戶點擊標題時,所有的feed標題將顯示,一個詳細視圖將顯示標題,描述和圖像,但面臨着性能問題,因爲應用程序花費時間加載圖像UIImageView,因爲圖像來自下面的圖像url是我的代碼。從url加載圖像到uiimageview使iphone應用程序性能下降

NSURL *url = [NSURL URLWithString:imageURL]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
UIImageView *subview = [[UIImageView alloc] initWithFrame:CGRectMake(110,10,100,80)]; 
[subview setImage:[UIImage imageWithData:data]]; 
[cell addSubview:subview]; 
[subview release]; 

在這段代碼imageurl是來自rss和處理到UIImageView來顯示圖像。如果我刪除這個特定的代碼,性能很好,因爲所有的數據都是文本。

因此,如何才能從url中獲取圖像並快速顯示到UIImageView控件,而不會丟失性能或顯示活動指示器,直到完全分開加載圖像。請幫助我。

+1

請修正你的鍵盤上的Shift鍵。 :) – rmaddy

回答

3

切勿在主線程上執行網絡調用。 Apple爲此提供了一個有用的示例應用程序。請參閱LazyTableImages示例應用程序以正確加載背景中的圖像。

1

嗨,你還可以使用第三方的類名爲AsyncImageView

您的問題或者您也可以創建自己的類有NSURLConnectionDelegate是downloads an image

這些解決方案還可以解決你的問題,當用戶界面是鎖定由於同步網址請求。

+0

感謝您的糾正。 – objectiveCarlo

0

你可以試試這個,

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^(void) { 
    [self loadImage]; 
}); 

-(void) loadImage 
{ 
    NSURL *url = [NSURL URLWithString:imageURL]; 
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    UIImageView *subview = [[UIImageView alloc] initWithFrame:CGRectMake(110,10,100,80)]; 
    [subview setImage:[UIImage imageWithData:data]]; 
    [cell addSubview:subview]; 
    [subview release]; 

} 

感謝

-1

你可以試試這個

//in .h file 

IBOutlet UIImageView *imgTest; 

-(IBAction)buttonTapped:(id)sender; 
-(void)LoadImage:(NSString *) irlString; 
-(void)setImage:(NSData *) imgData; 

//in .m file write the following code: 

-(IBAction)buttonTapped:(id)sender 
{ 
    [self performSelectorOnMainThread:@selector(LoadImage:) withObject:@"http://www.google.com/images/errors/logo_sm.gif" waitUntilDone:NO]; 
} 

-(void)LoadImage:(NSString *) urlString 
{ 
    NSURL *imgURL=[NSURL URLWithString:urlString]; 
    NSData *imgData=[NSData dataWithContentsOfURL:imgURL]; 
    [self performSelectorInBackground:@selector(setImage:) withObject:imgData]; 
} 

-(void)setImage:(NSData *) imgData; 
{ 
    imgTest.image=[UIImage imageWithData:imgData]; 
} 

希望這會幫助你。

1

看看here

[DLImageLoader loadImageFromURL:imageURL 
          completed:^(NSError *error, NSData *imgData) { 
           imageView.image = [UIImage imageWithData:imgData]; 
           [imageView setContentMode:UIViewContentModeCenter]; 

          }]; 
+0

這只是一個非常有用的圖書館。 (1)下載文件(2)放到你的項目中(3)使用你上面看到的命令。這個圖書館吃所有其他圖書館圖像下載**十幾十十分......如此優雅,如此堅實。它可以做所有的事情,緩存,作品。很簡單........... – Fattie

相關問題