2013-03-14 44 views
0

我遇到了在應用程序中加載內容的問題,我發現應用程序提取了數據,但圖像需要大量時間加載,是否有加載的可能性圖像後綴。代碼如下:由於圖像加載問題導致應用程序放慢

NSDictionary *dict=[discussionArray objectAtIndex:indexPath.row]; 
UIImageView *avatarimage = (UIImageView *)[cell viewWithTag:4]; 
NSString *photoStrn=[dict objectForKey:@"photo"]; 

dispatch_async(dispatch_get_global_queue(0,0), ^{ 
        NSString *u=[NSString stringWithFormat:@"http://%@",photoStrn]; 
        NSURL *imageURL=[NSURL URLWithString:u]; 
        NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
        dispatch_sync(dispatch_get_main_queue(), ^{ 
        UIImage *dpImage = [UIImage imageWithData:imageData]; 
        if (dpImage==nil) 
        { 
        dpImage = [UIImage imageNamed:@"profileImage.png"]; 
        } 
        avatarimage.image = dpImage; 

     }); 

如果您想了解更多的細節,我會提供:)

+0

看到這樣一個http://stackoverflow.com/questions/9786018/loading-an-image-into-uiimage-asynchronously – Balu 2013-03-14 11:02:16

+0

看看這一個回答:http://stackoverflow.com/a/15270523/2106940 – Jeremy 2013-03-14 11:04:15

回答

4

可以使用GCD這樣做的:

dispatch_async(dispatch_get_global_queue(0,0), ^{ 
    for (NSDictionary *dic in discussionArray) 
    { 
     NSString *photoStr=[dic objectForKey:@"photo"]; 
     NSString * photoString=[NSString stringWithFormat:@"http://%@",photoStr]; 
     UIImage *dpImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:photoString]]]; 
     if (dpImage==nil) 
     { 
      dpImage = [UIImage imageNamed:@"profileImage.png"]; 
     } 
    } 
}); 
+0

我試過這種方法的網頁加載速度快:),但有一個問題是在滾動應用程序改變頭像圖像並重新加載圖像。我想我犯了一些錯誤,我正在更新上面的代碼。 – 2013-03-14 20:35:31

+0

@JamesMitchee我猜你正在使用tableView,並且在重新使用單元格時忘記將圖像重置爲默認值。 – Till 2013-03-14 20:38:14

+0

@我試過但沒有成功:( – 2013-03-14 20:56:43

0

獲取SDWebImage Here並補充說,在您的項目,包括

的UIImageView + WebCache.h

in class implementation file

UIImageView *imag=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)]; 
[imag setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[jsonarray objectAtIndex:indexPath.row]valueForKey:@"imgurl"]]] placeholderImage:[UIImage imageNamed:@"[email protected]"]]; 
[self.view addSubview:imag]; 
[imag release]; 

SDWebImage對於從URL加載圖像將更加有用。

希望這有助於!

0

詹姆斯,

這一行,

[NSData dataWithContentsOfURL:[NSURL URLWithString:photoString]]] 

你讓在主線程同步網絡調用。當前線程將掛起網絡呼叫完成。

解決方案是做一個異步網絡調用。 AFNetworking庫提供了一個非常好的類別來異步加載圖像:UIImageView+AFNetworking

相關問題