iOS网络编程(二) 自定义请求网络类----推荐用于需要请求过程片段数据

@Block传值

.h

#import <Foundation/Foundation.h>

typedef void(^MyBlock)(NSData *);
typedef void(^LengthBlock)(float);

@interface HMTMyCustomNetRequest : NSObject<NSURLConnectionDataDelegate>

@property (nonatomic,retain)NSMutableData * data;
@property (nonatomic,retain)NSURLConnection * connection;
@property (nonatomic,copy)MyBlock finishLoadBlock;
@property (nonatomic,copy)LengthBlock lengthBlock;

// GET请求方式
- (void)requestForGETWithUrl:(NSString *)urlString;

// POST请求方式
- (void)requestForPOSTWithUrl:(NSString *)urlString postData:(NSData *)data;

// 取消请求
- (void)cancelNSURLConnection;

@end
.m

#import "HMTMyCustomNetRequest.h"

@interface HMTMyCustomNetRequest (){
    
    NSUInteger leng;
    
}

@end

@implementation HMTMyCustomNetRequest

- (void)dealloc{
    
    RELEASE_SAFELY(_data);
    RELEASE_SAFELY(_connection);
    Block_release(_finishLoadBlock);
    Block_release(_lengthBlock);
    [super dealloc];
    
}

- (void)requestForGETWithUrl:(NSString *)urlString{
    
    NSURL * url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"GET"];
    
    /**
     *  Special Considerations
     During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.
     */
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)requestForPOSTWithUrl:(NSString *)urlString postData:(NSData *)data{
    
    NSURL * url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:data];
    
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    
}


#pragma mark - 取消协议异步方法调用(关键关键很关键,不做这一步经常出现崩溃的地方)
- (void)cancelNSURLConnection{
    
    /**
     *  如果数据在加载,但是因为其他一些原因,比如跳转页面做其他事,而不是正常的数据加载完成或者数据加载失败
     *  一定要手动取消网络请求连接
     *  Special Considerations
     *  During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the--
     *  ---connection finishes loading, fails, or is canceled.
     *  self.connection = [NSURLConnection connectionWithRequest:self delegate:self];
     *
     */
    [_connection cancel];
    self.connection = nil;
    
}

#pragma mark - 服务器开始给客户端回传数据,这个方法只会执行一次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    // 初始化接收数据的空data
    self.data = [NSMutableData data];
    
    // 取得数据总长度
    leng = response.expectedContentLength;
    
}

#pragma mark - 客户端持续接收数据,data是数据片段,整个数据分段返回,这个方法执行的次数取决于数据总长度[response expectedContentLength]
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    [self.data appendData:data];
    
    float progressLength = [self.data length] / (float)leng;
    
    if (_lengthBlock) {
        
        self.lengthBlock(progressLength);
        
    }
    
    //if (_finishLoadBlock) {
        
        //self.finishLoadBlock(_data);
       
    //}

}

#pragma mark - 数据完全下载成功,接收到完整数据
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    // 调用完整数据的block方法
    if (_finishLoadBlock) {
        
        self.finishLoadBlock(_data);
      
    }
    
}

#pragma mark - 数据下载失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    NSLog(@"请求网络出错:%@",error);
}

@end


@delegate代理传值

.h

#import <Foundation/Foundation.h>

@class HMTNetWorkRequest;
@protocol  NetWorkRequestDelegate<NSObject>

@optional

//netWork请求成功
- (void)netWorkRequest:(HMTNetWorkRequest *)request didSuccessfulReceiveData:(NSData *)data;

//netWork请求失败
- (void)netWorkRequest:(HMTNetWorkRequest *)request didFailed:(NSError *)error;

//获取netWork的下载进度
- (void)netWorkRequest:(HMTNetWorkRequest *)request withProgress:(CGFloat)progress;

@end


@interface HMTNetWorkRequest : NSObject<NSURLConnectionDataDelegate>

@property (nonatomic,assign) id<NetWorkRequestDelegate> delegate;
@property (nonatomic,retain)NSURLConnection * connection;

- (void)requestForGETWithUrl:(NSString *)urlString;

- (void)requestForPOSTWithUrl:(NSString *)urlString postData:(NSData *)data;

// 取消网络请求
- (void)cancelRequest;

@end
.m

#import "HMTNetWorkRequest.h"

@interface HMTNetWorkRequest (){

    NSUInteger _totalLength;

}

@property (nonatomic,retain)NSMutableData * receiveData;

@end

@implementation HMTNetWorkRequest

- (void)dealloc{

    RELEASE_SAFELY(_connection);
    RELEASE_SAFELY(_receiveData);
    [super dealloc];

}

#pragma mark - 不用的时候一定要取消
- (void)cancelRequest{

    [_connection cancel];
    self.connection = nil;
    self.delegate = nil;
    
}

- (void)requestForGETWithUrl:(NSString *)urlString{

    NSURL * url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"GET"];
    
    /**
     *  Special Considerations
     During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.
     */
    [NSURLConnection connectionWithRequest:request delegate:self];
    [request release];
}

- (void)requestForPOSTWithUrl:(NSString *)urlString postData:(NSData *)data{

    NSURL * url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:data];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [request release];
}

#pragma mark - 服务器开始给客户端回传数据,这个方法只会执行一次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    // 服务器开始回传数据,客户端需要创建一个空的,可变的Data对象,用于存储每次获取的数据片段
    self.receiveData = [NSMutableData data];
    
    // 取得请求数据的长度
    _totalLength = [response expectedContentLength];

}

#pragma mark - 客户端持续接收数据,data是数据片段,整个数据分段返回,这个方法执行的次数取决于数据总长度[response expectedContentLength]
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [self.receiveData appendData:data];
    
    CGFloat progress = [_receiveData length]/_totalLength;

    if ([_delegate respondsToSelector:@selector(netWorkRequest:withProgress:)]) {
        
        [_delegate netWorkRequest:self withProgress:progress];
    }
    
}


#pragma mark - 数据完全下载成功,接收到完整数据
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    if ([_delegate respondsToSelector:@selector(netWorkRequest:didSuccessfulReceiveData:)]) {
        
        [_delegate netWorkRequest:self didSuccessfulReceiveData:_receiveData];
    }
    
    self.receiveData = nil;
}


#pragma mark - 数据下载失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    NSLog(@"didFailWithError");

}

@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值