簡體   English   中英

將圖像從URL動態下載到UIImageVIew

[英]Downloading image from a url into a UIImageVIew dynamically

我試圖從URL中插入和映像到UIImageView。 我使用以下代碼來執行此操作。 運行程序時遇到困難

NSURL *url = [NSURL URLWithString:urlstring];

在下面的代碼中,它在該特定行上顯示“Thread 1:signal 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;

}

更改此代碼:

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這樣的圖像緩存庫會有很大的幫助,因為即使使用這個實現,你只需將下載過程推送到后台線程,這樣UI就不會被卡住,但你不會緩存任何東西。

嘗試這個

[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"]]]];

});

如果url是動態的話

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

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

NSData *data = [NSData dataWithContentsOfURL:url];

將加載imageData同步,這意味着主線程將被阻止。

使用github上的項目: SDWebImage進行圖像異步加載和緩存。

現在可能有更好的庫可以做到這一點,但我一直在為我的項目使用它,它運行良好: AsyncImageView 還有其他替代方案,如SDWebImage

但基本上,你不想使用

NSData *data = [NSData dataWithContentsOfURL:url];

因為它會阻止主線程直到下載圖像。 為避免這種情況,您可能希望使用異步方法,例如上面的兩個庫。

例如,使用AsyncImageView ,它變得如此簡單:

myImageView.imageURL = someNSURL;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM