基于AI实现对AFNetworking的封装

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

NS_ASSUME_NONNULL_BEGIN

typedef void (^NetworkSuccessBlock)(id responseObject);
typedef void (^NetworkFailureBlock)(NSError *error);

@interface NetworkManager : NSObject

@property (nonatomic, assign) NSUInteger maxRetryCount; // 最大重试次数
@property (nonatomic, assign) BOOL shouldCache;         // 是否启用响应缓存
@property (nonatomic, assign) BOOL shouldRefreshCache;  // 是否强制刷新缓存,忽略已有缓存

+ (instancetype)sharedManager;

// GET 请求方法
- (void)GET:(NSString *)URLString
 parameters:(nullable NSDictionary *)parameters
    headers:(nullable NSDictionary *)headers
    success:(NetworkSuccessBlock)success
    failure:(NetworkFailureBlock)failure;

// POST 请求方法
- (void)POST:(NSString *)URLString
  parameters:(nullable NSDictionary *)parameters
     headers:(nullable NSDictionary *)headers
     success:(NetworkSuccessBlock)success
     failure:(NetworkFailureBlock)failure;

// 取消所有正在进行的网络请求
- (void)cancelAllRequests;

@end

NS_ASSUME_NONNULL_END

// NetworkManager.m
#import "NetworkManager.h"

@interface NetworkManager ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;    // AFNetworking 会话管理器
@property (nonatomic, strong) NSCache<NSString *, id> *responseCache; // 响应缓存对象
@property (nonatomic, strong) dispatch_queue_t retryQueue;            // 用于序列化重试操作的队列

@end

@implementation NetworkManager

+ (instancetype)sharedManager {
    static NetworkManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        _sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _sessionManager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        _responseCache = [[NSCache alloc] init];
        _responseCache.countLimit = 100;
        
        _retryQueue = dispatch_queue_create("com.networkmanager.retry", DISPATCH_QUEUE_SERIAL);
        
        _maxRetryCount = 3;
        _shouldCache = NO;
        _shouldRefreshCache = NO;
    }
    return self;
}

/**
 执行 GET 请求
 @param URLString 请求的 URL 地址
 @param parameters 请求参数字典,可为空
 @param headers 自定义 HTTP 请求头,可为空
 @param success 请求成功的回调,返回响应数据
 @param failure 请求失败的回调,返回错误信息
 */
- (void)GET:(NSString *)URLString
 parameters:(nullable NSDictionary *)parameters
    headers:(nullable NSDictionary *)headers
    success:(NetworkSuccessBlock)success
    failure:(NetworkFailureBlock)failure {
    [self performRequestWithMethod:@"GET"
                        URLString:URLString
                       parameters:parameters
                          headers:headers
                          attempt:1
                          success:success
                          failure:failure];
}

/**
 执行 POST 请求
 @param URLString 请求的 URL 地址
 @param parameters 请求参数字典,可为空
 @param headers 自定义 HTTP 请求头,可为空
 @param success 请求成功的回调,返回响应数据
 @param failure 请求失败的回调,返回错误信息
 */
- (void)POST:(NSString *)URLString
  parameters:(nullable NSDictionary *)parameters
     headers:(nullable NSDictionary *)headers
     success:(NetworkSuccessBlock)success
     failure:(NetworkFailureBlock)failure {
    [self performRequestWithMethod:@"POST"
                        URLString:URLString
                       parameters:parameters
                          headers:headers
                          attempt:1
                          success:success
                          failure:failure];
}

/**
 通用请求执行方法,支持重试机制
 @param method HTTP 方法(如 "GET" 或 "POST")
 @param URLString 请求的 URL 地址
 @param parameters 请求参数字典,可为空
 @param headers 自定义 HTTP 请求头,可为空
 @param attempt 当前尝试次数,从 1 开始
 @param success 请求成功的回调,返回响应数据
 @param failure 请求失败的回调,返回错误信息
 */
- (void)performRequestWithMethod:(NSString *)method
                      URLString:(NSString *)URLString
                     parameters:(nullable NSDictionary *)parameters
                        headers:(nullable NSDictionary *)headers
                        attempt:(NSUInteger)attempt
                        success:(NetworkSuccessBlock)success
                        failure:(NetworkFailureBlock)failure {
    
    NSString *cacheKey = [self cacheKeyForURL:URLString parameters:parameters];
    
    if (self.shouldCache && !self.shouldRefreshCache) {
        id cachedResponse = [self.responseCache objectForKey:cacheKey];
        if (cachedResponse) {
            dispatch_async(dispatch_get_main_queue(), ^{
                success(cachedResponse);
            });
            return;
        }
    }
    
    NSMutableURLRequest *request = [[self.sessionManager.requestSerializer requestWithMethod:method
                                                                                 URLString:[[NSURL URLWithString:URLString] absoluteString]
                                                                                parameters:parameters
                                                                                     error:nil] mutableCopy];
    
    if (headers) {
        [headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
            [request setValue:value forHTTPHeaderField:key];
        }];
    }
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *dataTask = [self.sessionManager dataTaskWithRequest:request
                                                            uploadProgress:nil
                                                          downloadProgress:nil
                                                         completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (error) {
            [strongSelf handleFailureWithError:error
                                    URLString:URLString
                                   parameters:parameters
                                      headers:headers
                                       method:method
                                      attempt:attempt
                                      success:success
                                      failure:failure];
        } else {
            if (strongSelf.shouldCache) {
                [strongSelf.responseCache setObject:responseObject forKey:cacheKey];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                success(responseObject);
            });
        }
    }];
    
    [dataTask resume];
}

/**
 处理请求失败并决定是否重试
 @param error 失败的错误信息
 @param URLString 请求的 URL 地址
 @param parameters 请求参数字典
 @param headers 自定义 HTTP 请求头
 @param method HTTP 方法
 @param attempt 当前尝试次数
 @param success 请求成功的回调
 @param failure 请求失败的回调
 */
- (void)handleFailureWithError:(NSError *)error
                    URLString:(NSString *)URLString
                   parameters:(NSDictionary *)parameters
                      headers:(NSDictionary *)headers
                       method:(NSString *)method
                      attempt:(NSUInteger)attempt
                      success:(NetworkSuccessBlock)success
                      failure:(NetworkFailureBlock)failure {
    
    if (attempt < self.maxRetryCount) {
        NSTimeInterval delay = pow(2.0, attempt) * 0.5;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), self.retryQueue, ^{
            [self performRequestWithMethod:method
                                URLString:URLString
                               parameters:parameters
                                  headers:headers
                                  attempt:attempt + 1
                                  success:success
                                  failure:failure];
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            failure(error);
        });
    }
}

/**
 生成缓存键
 @param URLString 请求的 URL 地址
 @param parameters 请求参数字典
 @return 用于缓存的唯一键
 */
- (NSString *)cacheKeyForURL:(NSString *)URLString parameters:(NSDictionary *)parameters {
    NSString *paramsString = parameters ? [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]
                                                               encoding:NSUTF8StringEncoding] : @"";
    return [URLString stringByAppendingString:paramsString];
}

/**
 取消所有正在进行的网络请求
 */
- (void)cancelAllRequests {
    [self.sessionManager.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        for (NSURLSessionTask *task in dataTasks) {
            [task cancel];
        }
    }];
}

@end
posted @ 2025-03-02 16:06  CoderWGB  阅读(31)  评论(0)    收藏  举报