基于AFNetworking的封装的工具类
生活随笔
收集整理的這篇文章主要介紹了
基于AFNetworking的封装的工具类
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
基于AFNetworking的封裝的工具類MXERequestService
// // MXERequestService.h // testAFNetWorking // // Created by lujun on 2022/1/6. //#import <Foundation/Foundation.h>/** 請(qǐng)求類型的枚舉 */ typedef NS_ENUM(NSUInteger, MXEHttpRequestType){/** get請(qǐng)求 */MXEHttpRequestTypeGet = 0,/** post請(qǐng)求 */MXEHttpRequestTypePost };/**http通訊成功的block@param responseObject 返回的數(shù)據(jù)*/ typedef void (^MXEHTTPRequestSuccessBlock)(id responseObject);/**http通訊失敗后的block@param error 返回的錯(cuò)誤信息*/ typedef void (^MXEHTTPRequestFailedBlock)(NSError *error);//超時(shí)時(shí)間 extern NSInteger const kAFNetworkingTimeoutInterval;@interface MXERequestService : NSObject/*** 網(wǎng)絡(luò)請(qǐng)求的實(shí)例方法** @param type get / post (項(xiàng)目目前只支持這倆中)* @param urlString 請(qǐng)求的地址* @param parameters 請(qǐng)求的參數(shù)* @param successBlock 請(qǐng)求成功回調(diào)* @param failureBlock 請(qǐng)求失敗回調(diào)*/ + (void)requestWithType:(MXEHttpRequestType)typeurlString:(NSString *)urlStringparameters:(NSDictionary *)parameterssuccessBlock:(MXEHTTPRequestSuccessBlock)successBlockfailureBlock:(MXEHTTPRequestFailedBlock)failureBlock;/**取消隊(duì)列*/ +(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];//以下三項(xiàng)manager的屬性根據(jù)需要進(jìn)行配置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];// 設(shè)置超時(shí)時(shí)間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(@"取消隊(duì)列了");}}];}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(@"取消隊(duì)列了");}}];} }+ (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總結(jié)
以上是生活随笔為你收集整理的基于AFNetworking的封装的工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ios15使用纯代码计算cell的高度
- 下一篇: 软件工程师的十个“不职业”行为