IOS从网络上异步加载一系列的图片并显示在tableview上的例子

首先从服务器上加载数据:

   NSURL *url = [NSURL URLWithString:@“http://2.novelread.sinaapp.com/framework-sae/index.php“];
[self loadJsonData:url];
-(void) loadJsonData:(NSURL *)url
{
//    dispatch_async(kGlobalQueue, ^{
//        NSData *data = [NSData dataWithContentsOfURL:url];
//        [self performSelectorOnMainThread:@selector(parseJsonData:) withObject:data waitUntilDone:NO];
//    });
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    DownloadHelper *help = [[DownloadHelper alloc] initWithRequest:request];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(parseJsonData:) name:@"connectionFinished" object:help];
    [[help connection] start];
    
}


-(void) parseJsonData:(NSNotification *)n
{
    DownloadHelper* help = [n object];
    NSData *data = [help receivedData];
    NSError *error;
    NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
   
    for (int i=0; i < [json count]; i++) {
        NSArray *s = [json objectAtIndex:i];
        ShopData *shopdata = [[ShopData alloc] init];
        shopdata._id = [s objectAtIndex:0];
        shopdata.name = [s objectAtIndex:1];
        shopdata.url = [s objectAtIndex:2];
        shopdata.info = [s objectAtIndex:3];
        [self.myArray addObject:shopdata];
        [shopdata release];

    }
    [self.tableView reloadData];
}



我们可以看到请求的数据是这种格式,解析方式如上所示:
[["1","book","http://novelread-file.stor.sinaapp.com/book.png","Book"],["2","cunshangcunshu","http://novelread-file.stor.sinaapp.com/cunshangcunshu.png","村上"]]

然后使用

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [myArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *TableViewDynamicLoadIdentifier = @"TableViewDynamicLoadIdentifier";
	
	UITableViewCell *pCell = [tableView dequeueReusableCellWithIdentifier:TableViewDynamicLoadIdentifier];
	if (pCell == nil)
	{
        pCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
									   reuseIdentifier:TableViewDynamicLoadIdentifier] autorelease];
		pCell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
    
    NSInteger nRow = [indexPath row];
	ShopData *shopdata = [self.myArray objectAtIndex:nRow];
	
	pCell.textLabel.text = shopdata.name;
    pCell.detailTextLabel.text = shopdata.info;
    if (shopdata.appIcon) {
        pCell.imageView.image = shopdata.appIcon;
    }else{
        if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
		{
			[self startIconDownload:shopdata forIndexPath:indexPath];
		}

        pCell.imageView.image = [UIImage imageNamed:@"Placeholder"];
    }
	return pCell;
}
为了解决tableview用手往下拨的时候,图片能顺利加载,必须实现协议 UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}

- (void)loadImagesForOnscreenRows
{
    if ([self.shopList count] > 0)
    {
        NSArray *visiblePaths = [self.myTableView indexPathsForVisibleRows];//取得tableview可见的item
        for (NSIndexPath *indexPath in visiblePaths)
        {
            Shop *shop = [self.shopList objectAtIndex:indexPath.row];//得到tableview这个item对应的shop信息
            
            if (!shop.shopIcon) // avoid the app icon download if the app already has an icon
            {
                [self startIconDownload:shop forIndexPath:indexPath];//将indexPath作为key,去下载图片
            }
        }
    }
}

-(void)startIconDownload:(ShopData *)shopdata forIndexPath:(NSIndexPath *)indexPath{
    IconDownloader *iconDownloader = [imageDownloadProgress objectForKey:indexPath];
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = shopdata;
        iconDownloader.indexPathInTableView = indexPath;
        iconDownloader.delegate = self;
        [imageDownloadProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
        [iconDownloader release];
    }
}


-(void)appImageDidLoad:(NSIndexPath *)indexPath{
    IconDownloader *iconDownloader = [imageDownloadProgress objectForKey:indexPath];
    if (iconDownloader != nil)
    {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:iconDownloader.indexPathInTableView];
        
        // Display the newly loaded image
        cell.imageView.image = iconDownloader.appRecord.appIcon;
    }

}

以下是IconDownloader的实现:

- (void)startDownload
{
    self.activeDownload = [NSMutableData data];
    // alloc+init and start an NSURLConnection; release on completion/failure
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
                             [NSURLRequest requestWithURL:
                              [NSURL URLWithString:appRecord.url]] delegate:self];
    self.imageConnection = conn;
    [conn release];
}

- (void)cancelDownload
{
    [self.imageConnection cancel];
    self.imageConnection = nil;
    self.activeDownload = nil;
}


#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	// Clear the activeDownload property to allow later attempts
    self.activeDownload = nil;
    
    // Release the connection now that it's finished
    self.imageConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Set appIcon and clear temporary data/image
    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
    
    if (image.size.width != kAppIconHeight && image.size.height != kAppIconHeight)
	{
        CGSize itemSize = CGSizeMake(kAppIconHeight, kAppIconHeight);
		UIGraphicsBeginImageContext(itemSize);
		CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
		[image drawInRect:imageRect];
		self.appRecord.appIcon = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
    }
    else
    {
        self.appRecord.appIcon = image;
    }
    
    self.activeDownload = nil;
    [image release];
    
    // Release the connection now that it's finished
    self.imageConnection = nil;
        
    // call our delegate and tell it that our icon is ready for display
    [delegate appImageDidLoad:self.indexPathInTableView];
}


运行后的图是:





例子的代码可以在http://download.csdn.net/detail/baidu_nod/7518659下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值