iOS开发中对于NSURLRequest的封装详解手机开发

在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 ];

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/5116.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论