iphone:使用NSURLConnection下载网络图片
这是一个很基本的demo,直接看代码,你应该可以看得懂。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
IconDownloader.h =============================== @interface IconDownloader : NSObject { NSString *imageURLString; NSMutableData *activeDownload; NSURLConnection *imageConnection; } @property (nonatomic, retain) NSString *imageURLString; @property (nonatomic, retain) NSMutableData *activeDownload; @property (nonatomic, retain) NSURLConnection *imageConnection; - (void)startDownload; - (void)cancelDownload; @end IconDownloader.m ===================================== #import "IconDownloader.h" @implementation IconDownloader @synthesize activeDownload; @synthesize imageConnection; #pragma mark - (void)dealloc { [activeDownload release]; [imageConnection cancel]; [imageConnection release]; [super dealloc]; } - (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:imageURLString]] 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]; self.activeDownload = nil; [image release]; // Release the connection now that it's finished self.imageConnection = nil; } @end |

浙公网安备 33010602011771号