-->

Faster way to load an image from a URL and display

2020-07-22 18:34发布

问题:

I am using the following code to display an image in my ImageView:

   imgbackBG.image = [UIImage imageWithData:
                   [NSData dataWithContentsOfURL:
                    [NSURL URLWithString:[NSString stringWithFormat:@"http://%@",    [test.arrImagessplash objectAtIndex:[test.arrImages count]-4]]]]];

    4cing.com/mobile_app/uploads/pageicon/splash.png

The problem is that the code executes very slowly. Is there a way to load the image and display it in the ImageView more quickly? If so, how can I do this?

回答1:

Download the Files from here.....

https://github.com/nicklockwood/AsyncImageView

and use as the following way:

AsyncImageView *asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(30,32,100, 100)];   
[asyncImageView loadImageFromURL:[NSURL URLWithString:your url]];
[YourImageView addSubview:asyncImageView];
[asyncImageView release];


回答2:

The code you are using loading image on main thread. This will block the UI. use GCD async for loading images.

Here is the sample code:

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(q, ^{
            /* Fetch the image from the server... */
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *img = [[UIImage alloc] initWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                /* This is the main thread again, where we set the tableView's image to
                 be what we just fetched. */
                cell.imgview.image = img;
            });
        });


回答3:

Best way to used `NSOperationQueue` to load Image in background.
Here is the sample code:


    NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
    [myQueue addOperationWithBlock:^{
        UIImage *img =  [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@""]]]?:[UIImage imageNamed:@"defaultImage.png"];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            YourImageView.image = img;

        }];
    }];


回答4:

Use SdwebImage framework for Image Cache

https://github.com/rs/SDWebImage