码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 网络请求封装

时间:2020-05-22 19:16:41      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:queue   pat   interface   eve   ios   blog   priority   tar   and   

NetWorkManager.h

 

#import <Foundation/Foundation.h>

@interface NetWorkManager : NSObject

//文件下载
+(void)downFile:(NSString *)fileUrl
   succeedBlock:(void (^)(NSData * data))succeedblock
      failBlock:(void (^)(NSString * errorstr)) failblock;

//基于使用Protobuf的GET请求(heards自定义请求头参数)
+ (void)getForProtobuf:(NSString *)url
         requestParams:(NSData *)data
                heards:(NSDictionary *)header
          succeedBlock:(void (^)(NSData * data))succeedblock
             failBlock:(void (^)(NSString * errorstr)) failblock;
//基于使用压缩Protobuf的GET请求(heards自定义请求头参数)
+ (void)getForProtobufZip:(NSString *)url
            requestParams:(NSData *)data
                   heards:(NSDictionary *)header
             succeedBlock:(void (^)(NSData * data))succeedblock
                failBlock:(void (^)(NSString * errorstr)) failblock;
//基于使用Json的GET请求(heards自定义请求头参数)
+ (void)getForJson:(NSString *)url
     requestParams:(NSData *)data
            heards:(NSDictionary *)header
      succeedBlock:(void (^)(NSData * data))succeedblock
         failBlock:(void (^)(NSString * errorstr)) failblock;
//基于使用压缩Json的GET请求(heards自定义请求头参数)
+ (void)getForJsonZip:(NSString *)url
        requestParams:(NSData *)data
               heards:(NSDictionary *)header
         succeedBlock:(void (^)(NSData * data))succeedblock
            failBlock:(void (^)(NSString * errorstr)) failblock;


//基于使用Protobuf的POST请求(heards自定义请求头参数)
+ (void)postForProtobuf:(NSString *)url
          requestParams:(NSData *)data
                 heards:(NSDictionary *)header
           succeedBlock:(void (^)(NSData * data))succeedblock
              failBlock:(void (^)(NSString * errorstr)) failblock;
//基于使用压缩Protobuf的POST请求(heards自定义请求头参数)
+ (void)postForProtobufZip:(NSString *)url
             requestParams:(NSData *)data
                    heards:(NSDictionary *)header
              succeedBlock:(void (^)(NSData * data))succeedblock
                 failBlock:(void (^)(NSString * errorstr)) failblock;
//基于使用Json的POST请求(heards自定义请求头参数)
+ (void)postForJson:(NSString *)url
      requestParams:(NSData *)data
             heards:(NSDictionary *)header
       succeedBlock:(void (^)(NSData * data))succeedblock
          failBlock:(void (^)(NSString * errorstr)) failblock;
//基于使用压缩Json的POST请求(heards自定义请求头参数)
+ (void)postForJsonZip:(NSString *)url
         requestParams:(NSData *)data
                heards:(NSDictionary *)header
          succeedBlock:(void (^)(NSData * data))succeedblock
             failBlock:(void (^)(NSString * errorstr)) failblock;
@end

 

NetWorkManager.m

 

#import "NetWorkManager.h"
#import <zlib.h>

@implementation NetWorkManager


//文件下载
+(void)downFile:(NSString *)fileUrl
   succeedBlock:(void (^)(NSData * data))succeedblock
      failBlock:(void (^)(NSString * errorstr)) failblock{
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];
    [self request:urlRequest succeedBlock:succeedblock failBlock:failblock];
}
+ (void)getForProtobuf:(NSString *)url
         requestParams:(NSData *)data
         heards:(NSDictionary *)header
          succeedBlock:(void (^)(NSData * data))succeedblock
             failBlock:(void (^)(NSString * errorstr)) failblock{
    [self request:url hTTPMethod:@"GET" requestParams:data heards:header contentType:@"application/x-protobuf" needZip:NO succeedBlock:succeedblock failBlock:failblock];
}
+ (void)getForProtobufZip:(NSString *)url
            requestParams:(NSData *)data
            heards:(NSDictionary *)header
             succeedBlock:(void (^)(NSData * data))succeedblock
                failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"GET" requestParams:data heards:header contentType:@"application/x-protobuf" needZip:YES succeedBlock:succeedblock failBlock:failblock];
}
+ (void)getForJson:(NSString *)url
     requestParams:(NSData *)data
     heards:(NSDictionary *)header
      succeedBlock:(void (^)(NSData * data))succeedblock
         failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"GET" requestParams:data heards:header contentType:@"application/json" needZip:NO succeedBlock:succeedblock failBlock:failblock];
}
+ (void)getForJsonZip:(NSString *)url
        requestParams:(NSData *)data
        heards:(NSDictionary *)header
         succeedBlock:(void (^)(NSData * data))succeedblock
            failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"GET" requestParams:data heards:header contentType:@"application/json" needZip:YES succeedBlock:succeedblock failBlock:failblock];
}



+ (void)postForProtobuf:(NSString *)url
          requestParams:(NSData *)data
          heards:(NSDictionary *)header
           succeedBlock:(void (^)(NSData * data))succeedblock
              failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"GET" requestParams:data heards:header contentType:@"application/x-protobuf" needZip:NO succeedBlock:succeedblock failBlock:failblock];
}
+ (void)postForProtobufZip:(NSString *)url
             requestParams:(NSData *)data
             heards:(NSDictionary *)header
              succeedBlock:(void (^)(NSData * data))succeedblock
                 failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"POST" requestParams:data heards:header contentType:@"application/x-protobuf" needZip:YES succeedBlock:succeedblock failBlock:failblock];
}
+ (void)postForJson:(NSString *)url
      requestParams:(NSData *)data
      heards:(NSDictionary *)header
       succeedBlock:(void (^)(NSData * data))succeedblock
          failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"POST" requestParams:data heards:header contentType:@"application/json" needZip:NO succeedBlock:succeedblock failBlock:failblock];
}
+ (void)postForJsonZip:(NSString *)url
         requestParams:(NSData *)data
         heards:(NSDictionary *)header
          succeedBlock:(void (^)(NSData * data))succeedblock
             failBlock:(void (^)(NSString * errorstr)) failblock{
      [self request:url hTTPMethod:@"POST" requestParams:data heards:header contentType:@"application/json" needZip:YES succeedBlock:succeedblock failBlock:failblock];
}

+ (void)request:(NSString *)url
     hTTPMethod:(NSString *)method
  requestParams:(NSData *)data
         heards:(NSDictionary *)header
    contentType:(NSString*)contentType
        needZip:(BOOL)needZip
   succeedBlock:(void (^)(NSData * data))succeedblock
      failBlock:(void (^)(NSString * errorstr)) failblock{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setTimeoutInterval:10.0f];// 设置请求超时
    [request setHTTPMethod:method]; // 设置请求方法
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];//数据类型为proto格式
    if(header && [header.allKeys count]>0){
        for (NSString * key in header.allKeys) {
            NSString * value = [header objectForKey:key];
            [request setValue:value forHTTPHeaderField:key];//自定义请求头参数
        }
    }
    if(needZip){
        [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];//服务端支持gzip压缩
        NSData *dataTemp  = [self gzippedDataWithData:data];//压缩
        [request setHTTPBody:dataTemp];
    }else{
        [request setHTTPBody:data];
    }
    [self request:request succeedBlock:^(NSData *resultdata) {
        succeedblock(resultdata);
    } failBlock:^(NSString *errorstr) {
        failblock(errorstr);
    }];
}

+ (void)request:(NSURLRequest *)request
   succeedBlock:(void (^)(NSData * resultdata))succeedblock
      failBlock:(void (^)(NSString * errorstr)) failblock{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(error){
                    failblock(error.localizedFailureReason);
                }else if(data && [data length]>0){
                    succeedblock(data);
                }else{
                    failblock(@"data is null");
                }
            });
        }];
        [dataTask resume];
    });
}

+(NSData *)gzippedDataWithData:(NSData *)oldData
{
    float level = -0.1f;
    if (oldData.length == 0)
    {
        return oldData;
    }
    z_stream stream;
    stream.zalloc = Z_NULL;
    stream.zfree = Z_NULL;
    stream.opaque = Z_NULL;
    stream.avail_in = (uint)oldData.length;
    stream.next_in = (Bytef *)(void *)oldData.bytes;
    stream.total_out = 0;
    stream.avail_out = 0;

    static const NSUInteger ChunkSize = 16384;
    NSMutableData *output = nil;
    int compression = (level < 0.0f)? Z_DEFAULT_COMPRESSION: (int)(roundf(level * 9));
    if (deflateInit2(&stream, compression, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK)
    {
        output = [NSMutableData dataWithLength:ChunkSize];
        while (stream.avail_out == 0)
        {
            if (stream.total_out >= output.length)
            {
                output.length += ChunkSize;
            }
            stream.next_out = (uint8_t *)output.mutableBytes + stream.total_out;
            stream.avail_out = (uInt)(output.length - stream.total_out);
            deflate(&stream, Z_FINISH);
        }
        deflateEnd(&stream);
        output.length = stream.total_out;
    }
    return output;
}
@end

点个赞再走呗。。。

如有疑问,联系作者 

简书:这个我不知道诶

博客园:这个我不知道诶

技术图片

iOS 网络请求封装

标签:queue   pat   interface   eve   ios   blog   priority   tar   and   

原文地址:https://www.cnblogs.com/Yongersblog/p/12938667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!