Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images in background to optimize the loading in ios

I am trying to optimize the load in my application, in fact, I have a lot of images that loaded in my application, and I spend a lot of time waiting for a view controller to open, especially the first initial view which includes a lot of images.

I took a look at apple sample

but I cannot re-work the whole application, what I want is just to tell me specifically what should I do?, I implement?

in the tableview, where the cell is implemented cellforrowatindexpath:

 NSURL *imageURL = ......;
 NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
 UIImage *imageLoad;
 imageLoad = [[UIImage alloc] initWithData:imageData];
 imageView.image = imageLoad;

could I do something?

thank you for your help!

enter image description here

like image 926
CarinaM Avatar asked Jun 26 '13 11:06

CarinaM


2 Answers

Try this 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;
    });
});
like image 168
Ramu Pasupuleti Avatar answered Oct 16 '22 15:10

Ramu Pasupuleti


Yes, you can add placeholder image to it.

It will not slow down the scrolling and will load image accordingly with time.

Also import this file UIImageView+WebCache.m and MapKit Framework

Here is the link to download the files.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
    UIImageview*  iV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
   [iV setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"image_placeholder.gif"]];
   [cell.contentView addSubview:iV];
   [iV release];

}

Just clean, build and run.

like image 30
AtWork Avatar answered Oct 16 '22 16:10

AtWork