如何异步加载API / URL中的图像?

时间:2015-11-10 04:19:39

标签: ios objective-c asynchronous

我从存储图像URL的数组中同步获取图像,但它的工作速度非常慢。现在我想异步加载它们以便快速工作。

继承代码并提供编码答案。

#import "DetailViewController.h"
#import "FinalViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController
@synthesize jsonData;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =  @"Select a Photo";

    // Do any additional setup after loading the view.
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL *url = [NSURL URLWithString:@"http://json.code.com/albums/1/photos"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];


}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
    data1 = [[NSMutableData alloc] init];
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)theData
{
    [data1 appendData:theData];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    jsonArray1 = [NSJSONSerialization JSONObjectWithData:data1 options:nil error:nil];
    [mainTableView reloadData];

}


-(void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please make sure you are connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (int)numberOfSectionInTableView:(UITableView *)tableView
{
    return 1;
}

- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [jsonArray1 count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }

    cell.textLabel.text = [[jsonArray1 objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"URL : %@", [[jsonArray1 objectAtIndex:indexPath.row] objectForKey:@"url"]];

    NSURL *URL = [[NSURL alloc] initWithString:[[jsonArray1 objectAtIndex:indexPath.row] valueForKey:@"thumbnailUrl"]];

    NSData *URLData = [[NSData alloc] initWithContentsOfURL:URL];
    [[cell imageView]setImage:[UIImage imageWithData:URLData]];


    return cell;
}


-(void)tableView:(UITableView *)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FinalViewController *fvc = [[FinalViewController alloc] initWithNibName:@"FinalViewController" bundle:nil];
    fvc.jsonData2 = [jsonArray1 objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:fvc animated:YES];

}


@end

3 个答案:

答案 0 :(得分:0)

你可以这样做:

cell.tag = indexPath.row;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {

    NSData *imageData = [NSData dataWithContentsOfURL: URL];

    UIImage* image = [[UIImage alloc] initWithData:imageData];
    if (image) {
         dispatch_async(dispatch_get_main_queue(), ^{
             if (cell.tag == indexPath.row) {
                 cell.imageView.image = image;
                 [cell setNeedsLayout];
             }
         });
     }
});

参考:Asynchronous downloading of images for UITableView with GCD

答案 1 :(得分:0)

试试这个,希望它能帮到你

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    myCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[myCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

    dispatch_async(kBgQueue, ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]];
        if (imgData) {
            UIImage *image = [UIImage imageWithData:imgData];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    myCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                    if (updateCell)
                        updateCell.poster.image = image;
                });
            }
        }
    });
    return cell;
}

答案 2 :(得分:0)

只需简单地设置以下作品对我来说很好。

cell.imageView.image =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[imageArray objectAtIndex:i]]]]];

您可以按照要求使用活动指示器。只需将UIActivityIndicatorView拖放到UIImageView的{​​{1}}上,然后设置所需的约束即可。加载图像后,您可以将其设置为隐藏。

要以编程方式执行此操作,您可以将子视图添加到UITableViewCell中的图像视图中。加载图像后,您可以删除子视图。

UITableViewCell