簡單封裝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

愿編程讓這個世界更美好

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容