简单封装AFNetworking

注意:

1.创建继承自AFHTTPSessionManager的单例类;
2.下载任务里的重要方法:NSURL *cacheDirectoryPath = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [cacheDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
3.上传任务里的重要方法:[formData appendPartWithFileData:UIImagePNGRepresentation(image) name:imagekey fileName:@"01.png" mimeType:@"image/png"];

ViewController.m

#import "ViewController.h"
#import "Utils.h"

@interface ViewController ()

@end

@implementation ViewController

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *parameters = @{
                                 @"username" : @"haha",
                                 @"password" : @"123"
                                 };
    [Utils getWithPath:@"login.php" AndParameters:parameters success:^(id json) {

        NSLog(@"调用封装AFNetworking方法成功 = %@" , json);

    } failed:^(NSError *error) {

        NSLog(@"调用封装AFNetworking方法失败 error = %@" , error);

    }];
    
    //下载任务:
    [Utils downloadWithPath:@"laojie.mp3" success:^(id json) {
        
        NSLog(@"%@",json);
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    } progress:^(double progress) {
        
        NSLog(@"%@",@(progress));

    }];
    
    
    //上传任务:thumbName是后台的图片key值:这个key值里包含了图片的所有信息 , 如error = 0 , name = 01.png , size大小 , type类型为image/png , tmp_name位置等...:
    [Utils uploadImageWithPath:@"post/upload.php" parameters:nil thumbName:@"userfile" image:[UIImage imageNamed:@"01.png"] success:^(id json) {
        
        NSLog(@"%@",json);
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    } progress:^(double progress) {
        
        NSLog(@"%@",@(progress));
        
    }];
    
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

Utils.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

//成功回调:
typedef void(^HttpSuccessBlock)(id json);   //参数是一个字典或者是数组:
//失败回调:
typedef void(^HttpFaileduccessBlock)(NSError *error);
//进度回调:
typedef void(^HttpDownloadProgressBlock)(double progress);
//上传回调:
typedef void(^HttpUploadProgressBlock)(double progress);

@interface Utils : NSObject

/**
 GET请求

 @param path url请求路径
 @param parameters url请求参数  字典类型
 @param success 请求成功        返回字典或者数组
 @param failed 请求失败         返回错误信息
 */
+ (void)getWithPath:(NSString *)path AndParameters:(NSDictionary *)parameters success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed;


/**
 POST请求
 
 @param path url请求路径
 @param parameters url请求参数  字典类型
 @param success 请求成功        返回字典或者数组
 @param failed 请求失败         返回错误信息
 */
+ (void)postWithPath:(NSString *)path AndParameters:(NSDictionary *)parameters success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed;


/**
 下载任务
 
 @param path url 请求路径
 @param success  请求成功         返回字典或者数组
 @param failed   请求失败         返回错误信息
 @param progress 请求进度         返回进度信息
 */
+ (void)downloadWithPath:(NSString *)path success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed progress:(HttpDownloadProgressBlock)progress;


/**
 上传任务
 
 @param path url 请求路径
 @param parameters url请求参数  字典类型
 @param success  请求成功         返回字典或者数组
 @param failed   请求失败         返回错误信息
 @param progress 请求进度         返回进度信息
 */
+ (void)uploadImageWithPath:(NSString *)path parameters:(NSDictionary *)parameters thumbName:(NSString *)imagekey image:(UIImage *)image success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed progress:(HttpUploadProgressBlock)progress;

@end

Utils.m

//
//  Utils.m
//  05-二次封装AFN
//
//  Created by miaodong on 2017/10/7.
//  Copyright © 2017年 大欢. All rights reserved.
//

#import "Utils.h"
#import "AFNetworking/AFNetworking.h"

static NSString *kBaseUrl = @"http://192.168.1.34";
#pragma mark - AFHTTPClient
@interface AFHTTPClient : AFHTTPSessionManager

+ (instancetype)sharedClient;

@end

@implementation AFHTTPClient

#pragma mark - 单例方法
+ (instancetype)sharedClient
{
    static AFHTTPClient *client = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl] sessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        /**
         *  统一设置参数
         
         */
        //1.设置接受参数类型:
        client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",@"image/gif", nil];
        //2.安全策略:AFSSLPinningModeNone;
        client.securityPolicy = [AFSecurityPolicy defaultPolicy];
        
    });
    
    return client;
}

@end


#pragma mark - Utils
@interface Utils ()

@end

@implementation Utils

#pragma mark - GET请求
+ (void)getWithPath:(NSString *)path AndParameters:(NSDictionary *)parameters success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed;
{
    //获取完整的URL路径:
    NSString *url = [kBaseUrl stringByAppendingPathComponent:path];
    //GET请求不需要监听progress:
    [[AFHTTPSessionManager manager] GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"GET网络请求成功😄...");
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"GET网络请求失败😭...");

        failed(error);
        
    }];
}


#pragma mark - POST请求
+ (void)postWithPath:(NSString *)path AndParameters:(NSDictionary *)parameters success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed
{
    //获取完整的URL路径:
    NSString *url = [kBaseUrl stringByAppendingPathComponent:path];
    //GET请求不需要监听progress:
    [[AFHTTPSessionManager manager] POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"progress = %@" , uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"GET网络请求成功😄...");
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"GET网络请求失败😭...");
        
        failed(error);
        
    }];
}


#pragma mark - 下载任务
+ (void)downloadWithPath:(NSString *)path success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed progress:(HttpDownloadProgressBlock)progress
{
    NSURLSessionDownloadTask *downloadTask = [[AFHTTPClient sharedClient] downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[kBaseUrl stringByAppendingPathComponent:path]]] progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //进度:
        progress(downloadProgress.fractionCompleted);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //destinationBlock是有一个NSURL返回值要求的:
        //获取沙盒cache路径:
        NSURL *cacheDirectoryPath = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [cacheDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (!error)
        {
            success(filePath.path);
        }
        else
        {
            failed(error);
        }
        
    }];
    
    //开启任务:
    [downloadTask resume];
}


#pragma mark - 上传任务
+ (void)uploadImageWithPath:(NSString *)path parameters:(NSDictionary *)parameters thumbName:(NSString *)imagekey image:(UIImage *)image success:(HttpSuccessBlock)success failed:(HttpFaileduccessBlock)failed progress:(HttpUploadProgressBlock)progress
{
    [[AFHTTPClient sharedClient] POST:[kBaseUrl stringByAppendingPathComponent:path] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:UIImagePNGRepresentation(image) name:imagekey 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) {
        
        failed(error);
        
    }];
}

@end

愿编程让这个世界更美好

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容