繁体   English   中英

通过NSURLConnection异步加载TableView图像

[英]Asynchronously Loading TableView Images via NSURLConnection

顾名思义,我正在尝试通过NSURLConnection异步加载tableview图像。 这里的问题是,当我向下滚动时,我的表视图倾向于在表视图中为多个国家/地区加载相同的标记图像,然后在滚动时为多个国家/地区加载不同的标记图像(因为在多个国家/地区具有相同的标记图像)备份。 我注意到,仅当我非常缓慢地滚动时,我才能获得不同国家的不同国旗图像,但是图像不正确。 我不太确定目前是什么问题。 这是我的代码:

#import "ViewController.h"

@implementation ViewController
@synthesize tableView;
@synthesize countryNamesArray;
@synthesize receivedData; 
@synthesize flagImage;
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{   
    countryNamesArray=[[NSArray alloc] initWithObjects:@"India",@"USA",@"Antarctica",@"Brazil",@"Canada",@"China",@"France",@"Germany",@"Italy",@"Japan",@"Kenya",@"Malaysia",@"Mexico",@"South Africa",@"United Kingdom",@"Vietnam",nil];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

-(NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section{
    return 16;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    // receivedData is declared as a method instance elsewhere


    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    flagImage = [UIImage imageWithData: receivedData];
}

-(void)issueRequest:(NSString *)fullCountryImageURL{
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:fullCountryImageURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];


    } 
    else {
        // Inform the user that the connection failed.
    }
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"countryCell";
    UITableViewCell *cell=(UITableViewCell *) [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil){
        cell=[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

    // Create the request.


    NSString *flagImageURLPartOne = @"http://www.flagimage.com/";
    NSString *countryNumber = [NSString stringWithFormat:@"%i", indexPath.row+1];
    NSString *flagImageURLPartTwo = @".png";
    NSString *fullCountryImageURL = [NSString stringWithFormat:@"%@%@%@", flagImageURLPartOne, countryNumber, flagImageURLPartTwo];

    [self issueRequest:fullCountryImageURL];

    cell.imageView.image = flagImage;
    cell.textLabel.text= [countryNamesArray objectAtIndex:indexPath.row];

    return cell;
}

-(void) tableView:(UITableView *) tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}


@end

有人有想法么?

您必须以某种方式通过数据结构将flagImage与国家/地区名称相关联。

看看tableView:cellForRowAtIndexPath:发生了什么tableView:cellForRowAtIndexPath:您异步触发对图像的请求,然后将当前flagImage分配给单元格的图像视图。 但是NSURLConnection委托方法会在将来某个不确定的时间flagImage并在那时重新分配flagImage

您当前在tableView:cellForRowAtIndexPath:适用于同步NSURLConnection但是异步委托回叫使您陷入困境。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM