IOS–簡單的網路NSURLConnection的使用

來源:互聯網
上載者:User
#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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.