iphone - 目标 - C : Loading image from URL?

标签 iphone objective-c uitableview uiimageview

抱歉问题标题。我找不到合适的标题。

当我打开 UITableView 时,我从 url 获取了 UITableView 内容图像,直到加载图像并且需要很长时间后, View 才会显示。

我通过 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;

抱歉,我的英语很弱。

最佳答案

在单独的线程上执行 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];
}

关于iphone - 目标 - C : Loading image from URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12140662/

相关文章:

objective-c - UITableView 帧高动画故障

objective-c - UITableView setContentOffset但不滚动tableView吗?

ios - 删除 TableView 单元格按钮崩溃

ios - 使其他音频安静的音效 iOS AVAudio

iphone - 像素空间中的 OpenGL 纹理坐标

iphone - 从 EAGLView 录制的视频上传到 YouTube 时会翻转

objective-c - 从相机胶卷创建一个 UIImages 数组

iphone - 如何更改 entitlements.plist 的路径

ios - UIDocumentInteractionController 防止 'Open in' 工作表中的 Airdrop

objective-c - 如何防止在 Objective-C 中为非物理属性创建变量?