IOS-간단한 네트워크 NSURLconnection 사용

2468 단어
#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

좋은 웹페이지 즐겨찾기