基于AFNetworking的封装的工具类
生活随笔
收集整理的這篇文章主要介紹了
基于AFNetworking的封装的工具类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于AFNetworking的封裝的工具類MXERequestService
// // MXERequestService.h // testAFNetWorking // // Created by lujun on 2022/1/6. //#import <Foundation/Foundation.h>/** 請求類型的枚舉 */ typedef NS_ENUM(NSUInteger, MXEHttpRequestType){/** get請求 */MXEHttpRequestTypeGet = 0,/** post請求 */MXEHttpRequestTypePost };/**http通訊成功的block@param responseObject 返回的數據*/ typedef void (^MXEHTTPRequestSuccessBlock)(id responseObject);/**http通訊失敗后的block@param error 返回的錯誤信息*/ typedef void (^MXEHTTPRequestFailedBlock)(NSError *error);//超時時間 extern NSInteger const kAFNetworkingTimeoutInterval;@interface MXERequestService : NSObject/*** 網絡請求的實例方法** @param type get / post (項目目前只支持這倆中)* @param urlString 請求的地址* @param parameters 請求的參數* @param successBlock 請求成功回調* @param failureBlock 請求失敗回調*/ + (void)requestWithType:(MXEHttpRequestType)typeurlString:(NSString *)urlStringparameters:(NSDictionary *)parameterssuccessBlock:(MXEHTTPRequestSuccessBlock)successBlockfailureBlock:(MXEHTTPRequestFailedBlock)failureBlock;/**取消隊列*/ +(void)cancelDataTask; + (void)postRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void(^)(NSDictionary *rootDict))successfailure:(void(^)(id error))failure; + (void)getRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void(^)(NSDictionary *rootDict))successfailure:(void(^)(id error))failure;@end // // MXERequestService.m // testAFNetWorking // // Created by lujun on 2022/1/6. //#import "MXERequestService.h" #import <AFNetworking/AFNetworking.h>NSInteger const kAFNetworkingTimeoutInterval = 10;@implementation MXERequestServicestatic AFHTTPSessionManager *aManager;+ (AFHTTPSessionManager *)sharedAFManager {static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{aManager = [AFHTTPSessionManager manager];//以下三項manager的屬性根據需要進行配置aManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/xml",@"text/json",@"text/plain",@"text/JavaScript",@"application/json",@"image/jpeg",@"image/png",@"application/octet-stream",nil];aManager.responseSerializer = [AFHTTPResponseSerializer serializer];// 設置超時時間aManager.requestSerializer.timeoutInterval = kAFNetworkingTimeoutInterval;});return aManager; }+ (void)requestWithType:(MXEHttpRequestType)typeurlString:(NSString *)urlStringparameters:(NSDictionary *)parameterssuccessBlock:(MXEHTTPRequestSuccessBlock)successBlockfailureBlock:(MXEHTTPRequestFailedBlock)failureBlock {if (urlString == nil) {return;}if (@available(iOS 9.0, *)) {urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];}else {urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];}if (type == MXEHttpRequestTypeGet){[[self sharedAFManager] GET:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {if (successBlock){id JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];successBlock(JSON);}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if (error.code !=-999) {if (failureBlock) {failureBlock(error);}}else{NSLog(@"取消隊列了");}}];}if (type == MXEHttpRequestTypePost){[[self sharedAFManager] POST:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {id JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];if (successBlock){successBlock(JSON);}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if (error.code !=-999) {if (failureBlock){failureBlock(error);}}else{NSLog(@"取消隊列了");}}];} }+ (void)cancelDataTask {NSMutableArray *dataTasks = [NSMutableArray arrayWithArray:[self sharedAFManager].dataTasks];for (NSURLSessionDataTask *taskObj in dataTasks) {[taskObj cancel];} }+ (void)postRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void (^)(NSDictionary * _Nonnull))successfailure:(void (^)(id _Nonnull))failure {[self requestWithType:MXEHttpRequestTypePost urlString:api parameters:param successBlock:^(id responseObject) {success(responseObject);} failureBlock:^(NSError *error) {failure(error);}]; }+ (void)getRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void (^)(NSDictionary * _Nonnull))successfailure:(void (^)(id _Nonnull))failure {[self requestWithType:MXEHttpRequestTypeGet urlString:api parameters:param successBlock:^(id responseObject) {success(responseObject);} failureBlock:^(NSError *error) {failure(error);}]; }+ (void)downloadRequestWithApi:(NSString *)urlparam:(NSDictionary *)paramprogress:(void(^)(NSInteger progress))progresssuccess:(void(^)(NSDictionary *rootDict))successfailure:(void(^)(id error))failure{NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];[[self sharedAFManager] downloadTaskWithRequest:requset progress:^(NSProgress * _Nonnull downloadProgress) { // progress(downloadProgress.);} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];return [NSURL fileURLWithPath:fullPath];} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {}]; }@end總結
以上是生活随笔為你收集整理的基于AFNetworking的封装的工具类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ios15使用纯代码计算cell的高度
- 下一篇: 软件工程师的十个“不职业”行为