目标 - C:从URL加载图像?(objective - C : Loading image fr

2019-07-31 04:49发布

对不起,我的问题标题。 我无法找到一个合适的标题。

UITableView从URL内容图像时,我打开UITableView查看并未出现,直到图像加载并沿着时间花费。

我通过PHP得到JSON的图像。

我想说明表,然后图像加载过程。

这是我的应用程序的代码:

NSDictionary *info = [json objectAtIndex:indexPath.row];
cell.lbl.text = [info objectForKey:@"title"];
NSString *imageUrl = [info objectForKey:@"image"];
cell.img.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
[cell.img.layer setBorderColor: [[UIColor blackColor] CGColor]];
[cell.img.layer setBorderWidth: 1.0];

return cell;

对不起我的英语薄弱。

Answer 1:

执行一个单独的线程web请求,不阻塞UI。 下面是使用的示例NSOperation 。 请记住,只有在主线程中更新UI,如图所示用performSelectorOnMainThread:

- (void)loadImage:(NSURL *)imageURL
{
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(requestRemoteImage:)
                                        object:imageURL];
    [queue addOperation:operation];
}

- (void)requestRemoteImage:(NSURL *)imageURL
{
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
    UIImage *image = [[UIImage alloc] initWithData:imageData];

    [self performSelectorOnMainThread:@selector(placeImageInUI:) withObject:image waitUntilDone:YES];
}

- (void)placeImageInUI:(UIImage *)image
{
    [_image setImage:image];
}


Answer 2:

你必须使用NSURLConnectionNSURLRequest 。 首先创建和(与占位符图像,存储在本地的应用程序也许)显示您的空表视图。 然后,你开始发送请求。 这些请求会在后台运行,并完成一个请求时,你(委托)将会收到通知。 在此之后,你便可以显示图片给用户。 尽量不要一次,如果你有很多他们的加载所有的图像。 不要加载是对用户不可见的那些,只有当他向下滚动加载这些。



Answer 3:

有一个UITableView lazy image loading ,苹果提供的示例: https://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html

希望这就是你要找的



Answer 4:

这是我们在我们的应用做很平常的事之一。

你只可以储存的URL在持久性存储阵列如或DB&可以得到使用操作队列更快地下载图像。 您可以设置优先级,随时取消等操作此外,应用程序响应时间会更快。



文章来源: objective - C : Loading image from URL?