2013-11-15 165 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