IOS--简单的网络NSURLConnection的使用

#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

你可能感兴趣的:(IOS--简单的网络NSURLConnection的使用)