2013-03-14 71 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

相关问题