2013-11-15 102 views
2

我想插入和图像到一个URL的UIImageView。我使用下面的代码来做到这一点。 运行程序时被卡住在从url下载图像到UIImageVIew动态

NSURL *url = [NSURL URLWithString:urlstring]; 

在下面的代码,它表明:在该特定的行“线程1信号SIGABRT”。 有人可以帮助我,并告诉如果我使用的格式是正确的或我做错了什么?

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"newoffer"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
if (cell==nil) 
{ 
    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 
NSDictionary *temp = [product objectAtIndex:indexPath.row]; 
UILabel *Label = (UILabel *)[cell viewWithTag:201]; 
Label.text = [temp objectForKey:@"item_name"]; 
UIImageView *Image = (UIImageView *)[cell viewWithTag:200]; 
NSString *urlstring=[temp objectForKey:@"image_url"]; 
NSURL *url = [NSURL URLWithString:urlstring]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
Image.image = [UIImage imageWithData:data]; 

return cell; 

} 
+3

如果可能,请在此处张贴您的网址 –

+0

如果在我的答案对您有帮助的情况下仍然面临任何问题,请将我的答案标记为正确。 –

回答

8

更改此代码:

NSURL *url = [NSURL URLWithString:urlstring]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
Image.image = [UIImage imageWithData:data]; 

要:

dispatch_queue_t myqueue = dispatch_queue_create("myqueue", NULL); 

    // execute a task on that queue asynchronously 
    dispatch_async(myqueue, ^{ 
NSURL *url = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
dispatch_async(dispatch_get_main_queue(), ^{ 
Image.image = [UIImage imageWithData:data]; //UI updates should be done on the main thread 
    }); 
    }); 

正如其他人所提到的,像SDWebImage影像缓存库将有很大的帮助,因为即使有这样的实现,你只需按下载处理后台线程,所以用户界面不会陷入困境,但你没有缓存任何东西。

+0

它工作...谢谢... – Spidy

0

NSData *data = [NSData dataWithContentsOfURL:url];

将加载的imageData同步的,这意味着主线程将被阻止。

使用github上的项目:SDWebImage进行图像异步加载和缓存。

0

现在可能有更好的库可以做到这一点,但我一直将它用于我的项目,效果很好:AsyncImageView。有喜欢SDWebImage

其他替代但基本上,你不希望使用

NSData *data = [NSData dataWithContentsOfURL:url]; 

,因为它会阻止主线程,直到图像被下载。为了避免这种情况,你可能想要使用异步的东西,比如上面的两个库。

myImageView.imageURL = someNSURL; 
3

试试这个

[image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.vbarter.com/images/content/1/9/19517.jpg"]]]]; 

对于异步下载

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

[image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.vbarter.com/images/content/1/9/19517.jpg"]]]]; 

}); 

如果网址是动态的,那么

例如,AsyncImageView,因为它变得容易

NSString *stringUrl; // this can be any valid url as string 

[image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:stringUrl]]]]; 
+0

@ Anand当我使用上面的代码它的作品。但是URL是动态的,它有所不同。所以当我把图像放入一个NSString对象时,会出现上述问题。 – Spidy