objective - C : Loading image from URL?

2020-06-27 09:10发布

Sorry for question title. I can not find a suitable title.

I have UITableView content images from url when i open the UITableView the View did not show until the images loaded and that takes along time.

I get the images from JSON by php.

I want to show the table and then images loading process.

This is code from my app:

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;

Sorry my english is weak.

4条回答
狗以群分
2楼-- · 2020-06-27 09:30

There is a UITableView lazy image loading example that Apple provided: https://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html

Hopefully it's what you were looking for

查看更多
欢心
3楼-- · 2020-06-27 09:37

This is among very common thing we do in our application.

You simply can have store the URLs in a persistent store e.g array or db & can get the images using Operation queue to download faster. You can set the priorities, cancel operations at anytime etc. Also, the application respond time will be quicker.

查看更多
\"骚年 ilove
4楼-- · 2020-06-27 09:39

Perform the web request on a separate thread, to not block the UI. Here is an example using NSOperation. Remember to only update the UI on the main thread, as shown with 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];
}
查看更多
一纸荒年 Trace。
5楼-- · 2020-06-27 09:40

You have to use NSURLConnection and NSURLRequest. First create and show your empty table view (maybe with placeholder images, that are stored locally in the app). Then you start sending requests. These requests will run in the background and you (the delegate) will be notified when a request is completed. After that you can show the image to the user. Try not to load all the images at once if you have a lot of them. And don't load the ones that are invisible to the user, only load those if he scrolls down.

查看更多
登录 后发表回答