iPhone 上实现异步加载图片并缓存代码

本文介绍了一种使用Swift语言实现的异步加载图片的方法,通过创建自定义的UIView子类AsyncImageView来异步下载并显示图片,避免了应用程序在图片下载期间阻塞或冻结。该方法适用于在UITableView或其他同时加载和显示多个图片场景中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

01    //
02    //  AsyncImageView.h
03    //  Postcard
04    //
05    //  Created by markj on 2/18/09.
06    //  Copyright 2009 Mark Johnson. You have permission to copy parts of this code into your own projects for any use.
07    //  www.markj.net
08    //
09
10    #import <UIKit/UIKit.h>
11
12
13    @interface AsyncImageView : UIView {
14        //could instead be a subclass of UIImageView instead of UIView, depending on what other features you want to
15        // to build into this class?
16
17        NSURLConnection* connection; //keep a reference to the connection so we can cancel download in dealloc
18        NSMutableData* data; //keep reference to the data so we can collect it as it downloads
19        //but where is the UIImage reference? We keep it in self.subviews – no need to re-code what we have in the parent class
20
21    }
22
23    - (void)loadImageFromURL:(NSURL*)url;
24    - (UIImage*) image;
25
26    @end

01    //
02    //  AsyncImageView.m
03    //  Postcard
04    //
05    //  Created by markj on 2/18/09.
06    //  Copyright 2009 Mark Johnson. You have permission to copy parts of this code into your own projects for any use.
07    //  www.markj.net
08    //
09
10    #import “AsyncImageView.h”
11
12
13    // This class demonstrates how the URL loading system can be used to make a UIView subclass
14    // that can download and display an image asynchronously so that the app doesn’t block or freeze
15    // while the image is downloading. It works fine in a UITableView or other cases where there
16    // are multiple images being downloaded and displayed all at the same time.
17
18    @implementation AsyncImageView
19
20    - (void)dealloc {
21        [connection cancel]; //in case the URL is still downloading
22        [connection release];
23        [data release];
24        [super dealloc];
25    }
26
27
28    - (void)loadImageFromURL:(NSURL*)url {
29        if (connection!=nil) { [connection release]; } //in case we are downloading a 2nd image
30        if (data!=nil) { [data release]; }
31
32        NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
33        connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //notice how delegate set to self object
34        //TODO error handling, what if connection is nil?
35    }
36
37
38    //the URL connection calls this repeatedly as data arrives
39    - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
40        if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
41        [data appendData:incrementalData];
42    }
43
44    //the URL connection calls this once all the data has downloaded
45    - (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
46        //so self data now has the complete image
47        [connection release];
48        connection=nil;
49        if ([[self subviews] count]>0) {
50            //then this must be another image, the old one is still in subviews
51            [[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
52        }
53
54        //make an image view for the image
55        UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
56        //make sizing choices based on your needs, experiment with these. maybe not all the calls below are needed.
57        imageView.contentMode = UIViewContentModeScaleAspectFit;
58        imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth || UIViewAutoresizingFlexibleHeight );
59        [self addSubview:imageView];
60        imageView.frame = self.bounds;
61        [imageView setNeedsLayout];
62        [self setNeedsLayout];
63
64        [data release]; //don’t need this any more, its in the UIImageView now
65        data=nil;
66    }
67
68    //just in case you want to get the image directly, here it is in subviews
69    - (UIImage*) image {
70        UIImageView* iv = [[self subviews] objectAtIndex:0];
71        return [iv image];
72    }
73
74    @end

  • [代码] [C/C++]代码

view source print?
01    - (UITableViewCell *)tableView:(UITableView *)tableView
02           cellForRowAtIndexPath:(NSIndexPath *)indexPath {
03
04        static NSString *CellIdentifier = @”ImageCell”;
05        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
06
07        if (cell == nil) {
08            cell = [[[UITableViewCell alloc]
09                  initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]
10                  autorelease];
11        } else {
12        AsyncImageView* oldImage = (AsyncImageView*)
13                 [cell.contentView viewWithTag:999];
14        [oldImage removeFromSuperview];
15        }
16
17        CGRect frame;
18        frame.size.width=75; frame.size.height=75;
19        frame.origin.x=0; frame.origin.y=0;
20        AsyncImageView* asyncImage = [[[AsyncImageView alloc]
21                   initWithFrame:frame] autorelease];
22        asyncImage.tag = 999;
23        NSURL* url = [imageDownload
24                   thumbnailURLAtIndex:indexPath.row];
25        [asyncImage loadImageFromURL:url];
26
27        [cell.contentView addSubview:asyncImage];
28
29        return cell;
30    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值