【问题标题】:objective - C : Loading image from URL?目标 - C:从 URL 加载图像?
【发布时间】:2012-08-27 10:56:23
【问题描述】:

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

当我打开 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;

对不起,我的英语很差。

【问题讨论】:

    标签: iphone objective-c uitableview uiimageview


    【解决方案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];
    }
    

    【讨论】:

    【解决方案2】:

    您必须使用NSURLConnectionNSURLRequest。首先创建并显示您的空表视图(可能使用本地存储在应用程序中的占位符图像)。然后你开始发送请求。这些请求将在后台运行,并且您(代理人)将在请求完成时收到通知。之后,您可以向用户显示图像。如果您有很多图像,请尽量不要一次加载所有图像。并且不要加载用户看不到的那些,只有在他向下滚动时才加载。

    【讨论】:

      【解决方案3】:

      Apple 提供了一个UITableView lazy image loading 示例:https://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html

      希望这就是你要找的东西

      【讨论】:

        【解决方案4】:

        这是我们在应用程序中非常常见的事情。

        您只需将 URL 存储在持久存储中,例如数组或数据库,并可以使用操作队列获取图像以更快地下载。您可以设置优先级,随时取消操作等。此外,应用程序响应时间会更快。

        【讨论】:

          猜你喜欢
          • 2016-03-04
          • 1970-01-01
          • 2015-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多