#import <Foundation/Foundation.h>@class MyConnection;//下載協議@protocol MyConnectionDelegate <NSObject>//下載完成- (void)MyConnectionDidFinish:(MyConnection*)con Data:(NSData*)data;//下載失敗- (void)MyConnectionDidFail:(MyConnection*)con;@end@interface MyConnection : NSObject<NSURLConnectionDataDelegate>{ NSMutableData* imageData;}- (id)initWithUrl:(NSString*)url Delegate:(id)delegate;@property (nonatomic,assign) id<MyConnectionDelegate> delegate;@property (nonatomic,retain) NSString* url;@property (nonatomic,assign) int tag;@end#import "MyConnection.h"#import "NSString+Hashing.h"@implementation MyConnection@synthesize url = _url;@synthesize delegate = _delegate;@synthesize tag = _tag;- (id)initWithUrl:(NSString *)url Delegate:(id)delegate{ if (self = [super init]) { self.delegate = delegate; self.url = url; imageData = [[NSMutableData alloc] init]; NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0]; [NSURLConnection connectionWithRequest:request delegate:self]; } return self;}- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [imageData appendData:data];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; //做緩衝 //http://192.168.88.8/wer/1.png //MD5 base64 // // /var/user/24234234/tmp/kjhaksdf87asd7f8a7sd8f78as7df //http://192.168.88.8/2.png //base64 //AAhttp://www.baidu.com/1.rarZZ //thrund://alkdjflashdfkjhasdkjf== NSString* path = NSHomeDirectory(); path = [NSString stringWithFormat:@"%@/tmp/%@",path,[self.url MD5Hash]]; [imageData writeToFile:path atomically:NO]; //使用下載完成的代理 [_delegate MyConnectionDidFinish:self Data:imageData];}- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; //使用下載失敗的代理 [_delegate MyConnectionDidFail:self];}- (void)dealloc{ [imageData release]; self.url = nil; [super dealloc];}@end