在ios开发中经常用到NSURLRequest类来进行url请求,通常有以下步骤

1.实例化NSURL;

2.实例化NSURLRequest;

3.连接[NSURLConnection connectionWithRequest:request delegate:self];

4.实现NSURLConnectionDataDelegate协议;

这样的话比较繁琐,可以对其进行封装

1.新建一个MyUrlRequest类

MyUrlRequest.h文件

    @interface MyUrlRequest : NSObject <NSURLConnectionDataDelegate> {   
        NSMutableData *_mData;//接收数据   
    }     
       
    @property (nonatomic, copy) NSString *urlStr;   
    @property (nonatomic, copy) void (^finishBlock)(NSData *data);//请求成功回调block   
    @property (nonatomic, copy) void (^failedBlick)();//请求失败回调block   
    @property (nonatomic, assign) BOOL isCache;//是否缓存   
       
    - (void)startRequest;//开始请求   
       
    @end  

MyUrlRequest.m文件
    #import "MyUrlRequest.h"   
    #import "NSString+Hashing.h"   
       
    @implementation QFURLRequest   
       
    @synthesize urlStr;   
    @synthesize finishBlock;   
    @synthesize failedBlick;   
    @synthesize isCache;   
       
    - (id)init {   
        if (self = [super init]) {   
            _mData = [[NSMutableData alloc] init];   
        }   
        return self;   
    }   
       
    - (void)startRequest {   
        //MyRequestManager里边autorelease掉,在这里可能出错,所以需要retain   
        [self retain];   
        if (self.isCache) {   
            //如果有缓存,则使用缓存   
            NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/tmp/%@", [self.urlStr MD5Hash]];   
            NSFileManager *manager = [NSFileManager defaultManager];   
            if ([manager fileExistsAtPath:path]) {   
                NSData *data = [NSData dataWithContentsOfFile:path];   
                self.finishBlock(data);   
                return;   
            }   
        }   
           
        NSURL *url = [NSURL URLWithString:self.urlStr];   
        NSURLRequest *request = [NSURLRequest requestWithURL:url];   
        [NSURLConnection connectionWithRequest:request delegate:self];   
    }   
    //实现NSURLConnectionDataDelegate协议   
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {   
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];   
    }   
       
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {   
        [_mData appendData:data];   
    }   
       
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {   
        [self release];   
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];   
        //写缓存   
        if (self.isCache) {   
            NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/tmp/%@", [self.urlStr MD5Hash]];   
            [_mData writeToFile:path atomically:YES];   
        }   
           
        self.finishBlock(_mData);   
    }   
       
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {   
        [self release];   
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];   
        self.failedBlick();   
    }   
       
    - (void)dealloc {   
        [_mData release];   
        self.finishBlock = nil;   
        self.failedBlick = nil;   
        [super dealloc];   
    }   
       
    @end  

2.新建一个MyRequestManager类

.h文件

    #import <Foundation/Foundation.h>   
    #import "MyUrlRequest.h"   
       
    @interface MyRequestManager : NSObject   
       
    + (void)requestWithUrl:(NSString *)urlString andIsCache:(BOOL)isCache finish:(void(^)(NSData *data))finishBlock failed:(void(^)())failedBlock;   
       
    @end  

.m文件
    #import "MyRequestManager.h"   
       
    @implementation MyRequestManager   
       
    + (void)requestWithUrl:(NSString *)urlString andIsCache:(BOOL)isCache finish:(void(^)(NSData *data))finishBlock failed:(void(^)())failedBlock   
    {   
        MyUrlRequest *request = [[[MyUrlRequest alloc] init] autorelease];   
        request.urlStr = urlString;   
        request.isCache = isCache;   
        request.finishBlock = finishBlock;   
        request.failedBlick =  failedBlock;   
        //在发送startRequest消息之后,该类方法结束,可能会对request发送autorelease消息,这样的话在request的startRequest方法中就可能会产生错误,所以要在startRequest方法中retain一下   
        [request startRequest];   
    }   
       
    @end  

这样的话,以后再发送请求就可以直接调用
[MyRequestManager requestWithUrl:(NSString *)urlString andIsCache:(BOOL)isCache finish:(void(^)(NSData *data))finishBlock failed:(void(^)())failedBlock ];

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

iOS异步请求下载图片详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。