Загрузить изображение в tableView с URL-адреса iphone SDK - PullRequest
6 голосов
/ 27 сентября 2011

У меня есть tableView и мне нужно загрузить изображение с URL. У меня есть массив, который содержит URL-адреса изображений, и когда страница загружается, мне нужно загрузить все изображения в табличное представление. Обратите внимание, что не с одного URL, есть массив с разными URL. Как я могу это реализовать? Пожалуйста, помогите

Спасибо.

Ответы [ 6 ]

34 голосов
/ 27 сентября 2011

Вы можете использовать GCD для загрузки изображений в фоновом потоке, например:

//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //this will start the image loading in bg
    dispatch_async(concurrentQueue, ^{        
        NSData *image = [[NSData alloc] initWithContentsOfURL:imageURL];

        //this will set the image when loading is finished
        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = [UIImage imageWithData:image];
        });
    });

Привет. Но вам, вероятно, нужно добавить dispatch_release (concurrentQueue); безусловно, нет утечки. - Франк 25 ​​августа в 19: 43

7 голосов
/ 27 сентября 2011

Вы можете использовать Lazy Loading, если хотите скачать изображения из интернета

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   //All you reusable cell implementation here.
   //Since your Images sizes differ. Keep a custom Imageview

    if(![imagesForCategories containsObject:indexPath])
    {    
        customImageView.image = [UIImage imageNamed:@"default-image.png"];
        NSMutableArray *arr = [[NSArray alloc] initWithObjects:[imageUrlArray objectAtIndex:indexPath.row],indexPath, nil];
        [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
        [arr release];
    }
    return cell;
}

- (void) loadImageInBackground:(NSArray *)urlAndTagReference 
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSURL *imgUrl=[[NSURL alloc] initWithString:[urlAndTagReference objectAtIndex:0]];
    NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
    UIImage *img = [UIImage imageWithData:imgData];
    [imgUrl release]; 
    NSMutableArray *arr = [[NSMutableArray alloc ] initWithObjects:img,[urlAndTagReference objectAtIndex:1], nil  ];
    [self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
    [arr release];
    [pool release];
}

- (void) assignImageToImageView:(NSMutableArray *)imgAndTagReference
{
    [imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
    UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
    UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
    profilePic.image = [imgAndTagReference objectAtIndex:0];

}
5 голосов
/ 27 сентября 2011

Вы можете использовать SDWebImage, который позволяет очень легко и быстро загружать изображения в UITableView.
https://github.com/rs/SDWebImage

4 голосов
/ 27 сентября 2011

Попробуйте этот код, imagearray содержит URL изображения

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [imagearray objectAtIndex:row]]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];


    cell.imageView.image =image;
    return cell;
}
3 голосов
/ 27 сентября 2011

Вам нужно создать собственную ячейку для отложенной загрузки. Это позволит вам загружать изображения правильно и без замораживания. Вот хороший пример, как это сделать: Асинхронная загрузка изображения

0 голосов
/ 08 января 2015

С afnetworki это слишком просто.

//afnetworking

#import "UIImageView+AFNetworking.h"

 [cell.iboImageView setImageWithURL:[NSURL URLWithString:server.imagen] placeholderImage:[UIImage imageNamed:@"qhacer_logo.png"]];
...