NSURLSession封装请求库

iOS9以后,苹果的数据请求用NSURLSession:

//
//  SkyHttpRequest.h
//  NSURLSessionDemo
//
//  Created by skyzizhu on 16/6/7.
//  Copyright © 2016年 skyzizhu. All rights reserved.
//
 
#import <Foundation/Foundation.h>
 
#import <CommonCrypto/CommonDigest.h>
 
@class SkyHttpRequest;
 
typedef void(^willSendRequestHandle)();
 
typedef void(^succeedRequestHandle)(NSMutableURLRequest *skyHttpRequest,id responseObject);
 
typedef void(^errorRequestHandle)(NSError *error);
 
@interface SkyHttpRequest : NSObject
 
{
    NSDictionary *_fieldValue;
    NSString *_mimeType;
}
//当前请求会话
 
@property (nonatomic,strong)NSURLSession *session;
 
//保存当前请求的内容
@property (nonatomic,strong)NSMutableData *responseData;
 
//当前的请求
//@property (nonatomic,strong)NSMutableURLRequest *request;
 
//初始化
+ (id)manager;
 
//添加头文件
-(void)addHeaderFieldWithFieldValue:(NSDictionary *)fieldValue;
 
//设置上传附件类型
-(void)setMimeType:(NSString *)mimeType;
 
//get请求
-(void)getRequestWithURL:(NSString *)url atParames:(NSDictionary *)parames atWillRequest:(willSendRequestHandle)willRequest atSucceedRequest:(succeedRequestHandle)succeedRequest atErrorRequest:(errorRequestHandle)errorRquest;
 
//post请求
-(void)postRequestWithURL:(NSString *)url atParames:(NSDictionary *)parames atWillRequest:(willSendRequestHandle)willRequest atSucceedRequest:(succeedRequestHandle)succeedRequest atErrorRequest:(errorRequestHandle)errorRquest;
 
//上传附件
-(void)postRequestWithURL:(NSString *)url atImageDatas:(NSArray *)datas atFormNames:(NSArray *)formNames atParames:(NSDictionary *)parames atWillRequest:(willSendRequestHandle)willRequest atSucceedRequest:(succeedRequestHandle)succeedRequest atErrorRequest:(errorRequestHandle)errorRquest;
 
@end
//
//  SkyHttpRequest.m
//  NSURLSessionDemo
//
//  Created by skyzizhu on 16/6/7.
//  Copyright © 2016年 skyzizhu. All rights reserved.
//
 
#import "SkyHttpRequest.h"
 
static NSString *DefaultMimeType = @"image/png";
 
const double SkyBaseRequestOutTimeValue = 20.0;
 
const double SkyExceptRequestOutTimeValue = 50.0;
 
@implementation SkyHttpRequest
 
+ (id)manager
{
    static dispatch_once_t onceQueue;
    static SkyHttpRequest *skyHttpRequest = nil;
    
    dispatch_once(&onceQueue, ^{
        skyHttpRequest = [[self alloc] init];
        skyHttpRequest.session = [NSURLSession sharedSession];
    });
    return skyHttpRequest;
}
 
-(void)addHeaderFieldWithFieldValue:(NSDictionary *)fieldValue
{
    _fieldValue = nil;
    if(fieldValue != nil){
        _fieldValue = [[NSDictionary alloc]initWithDictionary:fieldValue];
    }
}
 
-(void)setMimeType:(NSString *)mimeType
{
    _mimeType = nil;
    if(mimeType != nil){
        _mimeType = [NSString stringWithString:mimeType];
    }else{
        _mimeType = DefaultMimeType;
    }
}
 
//设置当前request的头部信息
-(void)setFieldValueWithRequest:(NSMutableURLRequest *)request
{
    if(_fieldValue != nil){
        for (NSString *fieldKey in _fieldValue) {
            [request setValue:_fieldValue[fieldKey] forHTTPHeaderField:fieldKey];
        }
        _fieldValue = nil;
    }
}
 
//append url key and value
 
-(NSMutableString *)getURLOperateWithURL:(NSString *)url atParams:(NSDictionary *)params
{
    NSMutableString *string = [NSMutableString stringWithFormat:@"%@?",url];
    for (NSString *key in params) {
        [string appendFormat:@"%@=%@&",key,params[key]];
    }
    [string deleteCharactersInRange:NSMakeRange([string length] - 1, 1)];
    return string;
}
 
-(NSData *)postDataWithParams:(NSDictionary *)params
{
    NSMutableString *string = [NSMutableString string];
    for (NSString *key in params) {
        [string appendFormat:@"%@=%@&",key,params[key]];
    }
    [string deleteCharactersInRange:NSMakeRange([string length] - 1, 1)];
    return [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
}
 
-(void)getRequestWithURL:(NSString *)url atParames:(NSDictionary *)parames atWillRequest:(willSendRequestHandle)willRequest atSucceedRequest:(succeedRequestHandle)succeedRequest atErrorRequest:(errorRequestHandle)errorRquest
{
    if(_session != nil){
        
        NSString *sourceUrl =  (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)url, NULL, NULL,  kCFStringEncodingUTF8 ));
        //url init
        NSString *resultURL = parames == nil ? sourceUrl : [self getURLOperateWithURL:sourceUrl atParams:parames];
        //request
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:resultURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:SkyBaseRequestOutTimeValue];
        [request setHTTPMethod:@"GET"];
        [self setFieldValueWithRequest:request];
        // 创建任务
        NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
            if(res.statusCode == 200){
                id jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                succeedRequest(request,jsonResult);
            }
            if(error != nil){
                errorRquest(error);
            }
        }];
        // 启动任务
        [task resume];
        if(willRequest != nil){
            willRequest();
        }
    }
}
 
-(void)postRequestWithURL:(NSString *)url atParames:(NSDictionary *)parames atWillRequest:(willSendRequestHandle)willRequest atSucceedRequest:(succeedRequestHandle)succeedRequest atErrorRequest:(errorRequestHandle)errorRquest
{
    if(_session != nil){
        
        NSString *sourceUrl =  (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)url, NULL, NULL,  kCFStringEncodingUTF8 ));
        //request
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:sourceUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:SkyBaseRequestOutTimeValue];
        [request setHTTPMethod:@"POST"];
        [self setFieldValueWithRequest:request];
        //body
        if(parames != nil){
            [request setHTTPBody:[self postDataWithParams:parames]];
        }
        // 创建任务
        NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
            if(res.statusCode == 200){
                id jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                succeedRequest(request,jsonResult);
            }
            if(error != nil){
                errorRquest(error);
            }
        }];
        // 启动任务
        [task resume];
        if(willRequest != nil){
            willRequest();
        }
    }
}
 
-(void)postRequestWithURL:(NSString *)url atImageDatas:(NSArray *)datas atFormNames:(NSArray *)formNames atParames:(NSDictionary *)parames atWillRequest:(willSendRequestHandle)willRequest atSucceedRequest:(succeedRequestHandle)succeedRequest atErrorRequest:(errorRequestHandle)errorRquest
{
    if(_session != nil){
        NSString *sourceUrl =  (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)url, NULL, NULL,  kCFStringEncodingUTF8 ));
        //request
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:sourceUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:SkyBaseRequestOutTimeValue];
        [request setHTTPMethod:@"POST"];
        [self setFieldValueWithRequest:request];
        [self postImageDataWithCurrentRequest:request Datas:datas atImageFormNames:formNames atParams:parames];
        
        // 创建任务
        NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
            if(res.statusCode == 200){
                id jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                succeedRequest(request,jsonResult);
            }
            if(error != nil){
                errorRquest(error);
            }
        }];
        // 启动任务
        [task resume];
        
        //will request
        if(willRequest != nil){
            willRequest();
        }
    }
}
 
#pragma mark - upload file event
-(void)postImageDataWithCurrentRequest:(NSMutableURLRequest *)request Datas:(NSArray *)datas atImageFormNames:(NSArray *)formNames atParams:(NSDictionary *)params
{
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    
    if([datas count] != [formNames count]){
        return;
    }
    NSMutableString *body=[[NSMutableString alloc]init];
    NSArray *keys= [params allKeys];
    for(int i=0;i<[keys count];i++){
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //添加分界线,换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称,换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[params objectForKey:key]];
    }
    
    //声明RequestData,用来放入http body
    NSMutableData *RequestData=[[NSMutableData alloc]init];
    //将params添加进去
    [RequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    for (int i = 0; i < [datas count]; i++) {
        //
        NSMutableString *subBody = [[NSMutableString alloc]init];
        //fileName
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[self sha1WithSource:[@(i) stringValue]]];
        ////添加分界线,换行
        [subBody appendFormat:@"%@\r\n",MPboundary];
        //声明pic字段,文件名
        [subBody appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",formNames[i],fileName];
        if(_mimeType != nil){
            [subBody appendFormat:@"Content-Type: %@\r\n\r\n",_mimeType];
        }else{
            //声明上传文件的格式
            [subBody appendFormat:@"Content-Type: %@\r\n\r\n",DefaultMimeType];
        }
        [body appendString:subBody];
        //将body字符串转化为UTF8格式的二进制
        [RequestData appendData:[subBody dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [RequestData appendData:datas[i]];
        //必加的分隔符,每一个data后边,http的规则
        [RequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    //声明结束符:--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //加入结束符--AaB03x--
    [RequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%ld", [RequestData length]] forHTTPHeaderField:@"Content-Length"];
    if([datas count] == 0 || datas == nil){
        [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
    }else{
        //设置http body
        [request setHTTPBody:RequestData];
    }
    //设置类型为空
    [self setMimeType:nil];
}
 
#pragma mark - enKey by sha1
 
- (NSString *)sha1WithSource:(NSString *)source
{
    NSData *data = [source dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}
 
@end

Leave a Reply

Required fields are marked *