zoukankan      html  css  js  c++  java
  • 对AFNetworking的二次封装

    HttpTool.h

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    
    typedef void(^HttpSuccessBlock)(id json);
    typedef void(^HttpFailureBlock)(NSError *error);
    typedef void(^HttpDownloadProgressBlock)(CGFloat progress);
    typedef void(^HttpUploadProgressBlock)(CGFloat progress);
    
    @interface HttpTool : NSObject
    
    /**
     get网络请求
    
     @param path url地址
     @param params url参数 NSDictionary类型
     @param success 请求成功 返回NSDictionary或NSArray
     @param failure 请求失败 返回NSError
     */
    + (void)getWithPath:(NSString *)path
                 params:(NSDictionary *)params
                success:(HttpSuccessBlock)success
                failure:(HttpFailureBlock)failure;
    
    /**
     post网络请求
     
     @param path url地址
     @param params url参数 NSDictionary类型
     @param success 请求成功 返回NSDictionary或NSArray
     @param failure 请求失败 返回NSError
     */
    + (void)postWithPath:(NSString *)path
                  params:(NSDictionary *)params
                 success:(HttpSuccessBlock)success
                 failure:(HttpFailureBlock)failure;
    
    /**
     下载文件
     
     @param path url路径
     @param success 下载成功
     @param failure 下载失败
     @param progress 下载进度
     */
    + (void)downloadWithPath:(NSString *)path
                     success:(HttpSuccessBlock)success
                     failure:(HttpFailureBlock)failure
                    progress:(HttpDownloadProgressBlock)progress;
    
    /**
     上传图片
     
     @param path url地址
     @param image UIImage对象
     @param thumbName imagekey
     @param params 上传参数
     @param success 上传成功
     @param failure 上传失败
     @param progress 上传进度
     */
    + (void)uploadImageWithPath:(NSString *)path
                         params:(NSDictionary *)params
                      thumbName:(NSString *)thumbName
                          image:(UIImage *)image
                        success:(HttpSuccessBlock)success
                        failure:(HttpFailureBlock)failure
                       progress:(HttpUploadProgressBlock)progress;
    
    
    @end

    HttpTool.m

    #import "HttpTool.h"
    #import "AFNetworking/AFNetworking.h"
    
    
    static NSString *kBaseUrl = SERVER_HOST;
    
    @interface AFHttpClient : AFHTTPSessionManager
    
    + (instancetype)sharedClient;
    
    @end
    
    @implementation AFHttpClient
    
    + (instancetype)sharedClient {
        
        static AFHttpClient *client = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
            
            client = [[AFHttpClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl] sessionConfiguration:configuration];
            // 接收参数类型
            client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", @"text/gif", nil];
            // 设置超时时间,默认60
            client.requestSerializer.timeoutInterval = 15;
            // 安全策略
            client.securityPolicy = [AFSecurityPolicy defaultPolicy];
        });
        
        return client;
    }
    
    @end
    
    @implementation HttpTool
    
    + (void)getWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure {
        
        // 获取完整的url路径
        NSString *url = [kBaseUrl stringByAppendingPathComponent:path];
        
        [[AFHttpClient sharedClient] GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            success(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failure(error);
            
        }];
    }
    
    + (void)postWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure {
        
        // 获取完整的url路径
        NSString *url = [kBaseUrl stringByAppendingPathComponent:path];
        
        [[AFHttpClient sharedClient] POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            success(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failure(error);
            
        }];
    }
    
    + (void)downloadWithPath:(NSString *)path success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure progress:(HttpDownloadProgressBlock)progress {
        
        // 获取完整的url路径
        NSString *url = [kBaseUrl stringByAppendingPathComponent:path];
        
        // 下载
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        
        NSURLSessionDownloadTask *downloadTask = [[AFHttpClient sharedClient] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            
            progress(downloadProgress.fractionCompleted);
            
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            
            // 获取沙盒cache路径
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            
            return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            
            if (error) {
                failure(error);
            } else {
                success(filePath.path);
            }
            
        }];
        
        [downloadTask resume];
    }
    
    + (void)uploadImageWithPath:(NSString *)path params:(NSDictionary *)params thumbName:(NSString *)thumbName image:(UIImage *)image success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure progress:(HttpUploadProgressBlock)progress {
        
        // 获取完整的url路径
        NSString *url = [kBaseUrl stringByAppendingPathComponent:path];
        
        NSData *data = UIImagePNGRepresentation(image);
        
        [[AFHttpClient sharedClient] POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            [formData appendPartWithFileData:data name:thumbName fileName:@"01.png" mimeType:@"image/png"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            progress(uploadProgress.fractionCompleted);
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failure(error);
        }];
    }
    
    
    @end
  • 相关阅读:
    Bootstrapbutton组
    Hadoop
    图像手工画效果【QT+OpenCV】
    经常使用传感器协议1:CJ/T-188 水表协议解析1
    神经网络的初识
    用队列实现栈
    sas数据导入终极汇总-之中的一个
    SPOJ 题目705 New Distinct Substrings(后缀数组,求不同的子串个数)
    怎样选择正确的HTTP状态码
    最新最全的iOS手机支付总结
  • 原文地址:https://www.cnblogs.com/xuzb/p/8872053.html
Copyright © 2011-2022 走看看