天天看點

IOS 開發 AFNetworking 網絡工具-網絡請求的三次封裝 OC版

NetworkTool.h

親測可用,能正常擷取資料(已背景傳回的json資料作為測試的)

//
//  NetworkTool.h
//
//  Created by zhouyu on 16/10/25.
//  Copyright © 2016年 mac All rights reserved.
//

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


typedef enum{
    requestTypeGET,
    requestTypePOST
}requestType;

@interface NetworkTool : AFHTTPSessionManager

//單例
+ (instancetype)shareNetworkTool;

//第一次封裝參數比較多,比較長
- (void)requestWithType:(requestType)type URLString:(nonnull NSString *)URLString parameters:(nullable id)parameters progress:(nullable void (^)(NSProgress *_Nonnull downloadProgress))downloadProgress success:(nullable void (^)(NSURLSessionDataTask *_Nullable task, id _Nullable responseObject))success
                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *_Nonnull error))failure;

//第二次封裝,簡化參數,把沒有用的progress參數去掉
- (void)requestWithType:(requestType)type URLString:(nonnull NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(id _Nullable responseObject))success  failure:(nullable void (^)(NSError *_Nonnull error))failure;

//第三次封裝,直接使用類方法,外部調用單例都不用建立
+ (void)requestWithType:(requestType)type URLString:(nonnull NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(id _Nullable responseObject))success  failure:(nullable void (^)(NSError *_Nonnull error))failure;
@end
           

NetworkTool.m

//
//  NetworkTool.m
//
//  Created by zhouyu on //
//  Copyright © 年 mac All rights reserved.
//

#import "NetworkTool.h"

static NetworkTool *instance;

@implementation NetworkTool

+ (instancetype)shareNetworkTool {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkTool alloc]init];
        //  讓AFN預設也支援接收text/html檔案類型
        instance.responseSerializer.acceptableContentTypes
        = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    });
    return instance;
}

//MARK: 一次封裝的網絡工具類
- (void)requestWithType:(requestType)type URLString:(NSString *)URLString parameters:(nullable id)parameters progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure{
    if (type == requestTypeGET) {
        [instance GET:URLString parameters:parameters progress:downloadProgress success:success failure:failure];
    } else if (type == requestTypePOST) {
        [instance POST:URLString parameters:parameters progress:downloadProgress success:success failure:failure];
    }
}

//MARK: 二次封裝的網絡工具類
- (void)requestWithType:(requestType)type URLString:(nonnull NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(id _Nullable responseObject))success  failure:(nullable void (^)(NSError *_Nonnull error))failure{
    //(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
    void (^orginalSuccess)(NSURLSessionDataTask * _Nullable, id  _Nullable) = ^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
//        success((NSDictionary *)responseObject);
        success(responseObject);
    };
    //(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
    void (^orginalFailure)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    };
    [self requestWithType:type URLString:URLString parameters:parameters progress:nil success:orginalSuccess failure:orginalFailure];
}

//MARK: 三次封裝的網絡工具類
+ (void)requestWithType:(requestType)type URLString:(nonnull NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(id _Nullable responseObject))success  failure:(nullable void (^)(NSError *_Nonnull error))failure {
    [[NetworkTool shareNetworkTool] requestWithType:type URLString:URLString parameters:parameters success:success failure:failure];
}
           

項目實測

//網絡請求
- (void)addNetworkData {
    NSString *URLString = [NSString stringWithFormat:@"%@",BaseURLString];

    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];

    NSDictionary *parameters = @{
                                 @"token":token
                                 };
    //使用第三次封裝的類方法--類名直接調用,簡潔明了                             
        [NetworkTool requestWithType:requestTypePOST URLString:URLString parameters:parameters success:^(id  _Nullable responseObject) {
    ZYLog(@"%@",responseObject);
    } failure:^(NSError *_Nonnull error) {

    }];
}
           

ZYLog(@”%@”,responseObject);的輸出結果

IOS 開發 AFNetworking 網絡工具-網絡請求的三次封裝 OC版
// MARK: 彈框
- (void)sendUIAlertControllerWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)( * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}
           

調用第一次封裝的效果

[[NetworkTool shareNetworkTool] requestWithType:requestTypePOST URLString:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        //處理傳回的json

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self sendUIAlertControllerWithTitle:@"使用者資訊擷取失敗" message:@"網絡延遲/系統繁忙"];
    }];
           

調用第二次封裝的效果

[[NetworkTool shareNetworkTool] requestWithType:requestTypePOST URLString:URLString parameters:parameters success:^(id  _Nullable responseObject) {

        //傳回的資料處理
    } failure:^(NSError * _Nonnull error) {
        [self sendUIAlertControllerWithTitle:@"使用者資訊擷取失敗" message:@"網絡延遲/系統繁忙"];
    }];