您好,登錄后才能下訂單哦!
這個封裝類包含了GET請求,POST請求,上傳圖片,上傳多張圖片,下載圖片,判斷網絡是否可用等功能。
#import <Foundation/Foundation.h> @interface HttpUtil : NSObject typedef NS_ENUM(NSInteger, NetworkReachabilityStatus) { NetworkReachabilityStatusUnknown = -1, NetworkReachabilityStatusNotReachable = 0, NetworkReachabilityStatusReachableViaWWAN = 1, NetworkReachabilityStatusReachableViaWiFi = 2, }; // GET請求 + (void)getWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError * error))failure; // POST請求 + (void)postWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure; // 上傳圖片 + (void)uploadWithURLString:(NSString *)URLString parameters:(id)parameters uploadData:(NSData *)uploadData uploadName:(NSString *)uploadName success:(void (^)())success failure:(void (^)(NSError *))failure; // 上傳多張圖片 + (void)uploadMostImageWithURLString:(NSString *)URLString parameters:(id)parameters uploadDatas:(NSArray *)uploadDatas uploadName:(NSString *)uploadName success:(void (^)())success failure:(void (^)(NSError *))failure; +(void)DownLoadWithUrlString:(NSString *)URLString parameters:(id)parameters progress:(void (^)(id))progress success:(void(^)(NSURL *filePath))success; +(void)setReachabilityStatusChangeBlock:(void(^)(NetworkReachabilityStatus status))block; +(void)stopMonitoring; +(Boolean)JudgeNetisConnect; @end
#import "HttpUtil.h" #import "AFNetworking.h" @implementation HttpUtil #pragma mark -- GET請求 -- + (void)getWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError * error))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer.timeoutInterval = 10; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil]; [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (responseObject) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (error) { failure(error); } }]; } #pragma mark -- POST請求 -- + (void)postWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]]; manager.requestSerializer.timeoutInterval = 10; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil]; [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; } #pragma mark -- 上傳圖片 -- + (void)uploadWithURLString:(NSString *)URLString parameters:(id)parameters uploadData:(NSData *)uploadData uploadName:(NSString *)uploadName success:(void (^)())success failure:(void (^)(NSError *))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil]; [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id< AFMultipartFormData > _Nonnull formData) { [formData appendPartWithFileData:uploadData name:uploadName fileName:uploadName mimeType:@"image/png"]; } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; } // 上傳多張圖片 uploadDatas 圖片的data集合 // uploadName 文件名稱 最好以xxx1 xxx2 表示 image1 image2 + (void)uploadMostImageWithURLString:(NSString *)URLString parameters:(id)parameters uploadDatas:(NSArray *)uploadDatas uploadName:(NSString *)uploadName success:(void (^)())success failure:(void (^)(NSError *))failure{ AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil]; [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id< AFMultipartFormData > _Nonnull formData) { for (int i=0; uploadDatas.count; i++) { NSString *imageName = [NSString stringWithFormat:@"%@[%i]", uploadName, i]; [formData appendPartWithFileData:uploadDatas[i] name:uploadName fileName:imageName mimeType:@"image/png"]; } } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; } +(void)DownLoadWithUrlString:(NSString *)URLString parameters:(id)parameters progress:(void (^)(id))progress success:(void(^)(NSURL *filePath))success { //1.創建管理者對象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; URLString=[self DownLoadUrlWithParams:URLString WithNSDictionaryParams:parameters]; NSLog(@"DownLoadFileUrl %@",URLString); NSURL *url = [NSURL URLWithString:URLString]; //3.創建請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //下載任務 NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { if (progress) { progress(downloadProgress); } } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { // //下載地址 // //設置下載路徑,通過沙盒獲取緩存地址,最后返回NSURL對象 NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; filePath=[filePath stringByAppendingPathComponent:@"DFU.zip"]; return [NSURL fileURLWithPath:filePath]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { if (success) { success(filePath); } }]; //開始啟動任務 [task resume]; } //因為下載的方法不能夠直接填寫dict參數進去,所以只有使用這種方法拼接參數進去 +(NSString *)DownLoadUrlWithParams:(NSString*)url WithNSDictionaryParams:(NSDictionary *)params{ // 初始化參數變量 NSString *body=@""; // 快速遍歷參數數組 NSString* appendUrl; for(id key in params) { NSLog(@"key :%@ value :%@", key, [params objectForKey:key]); body = [body stringByAppendingString:key]; body = [body stringByAppendingString:@"="]; body = [body stringByAppendingString:[params objectForKey:key]]; body = [body stringByAppendingString:@"&"]; } // 處理多余的&以及返回含參url if (body.length > 1) { // 去掉末尾的& body = [body substringToIndex:body.length - 1]; // 返回含參url } appendUrl=[url stringByAppendingString:body]; return appendUrl; } +(void)setReachabilityStatusChangeBlock:(void(^)(NetworkReachabilityStatus status))block{ //監測網絡狀態 AFNetworkReachabilityManager *netMan = [AFNetworkReachabilityManager sharedManager]; [netMan setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { // 未知網絡 case AFNetworkReachabilityStatusUnknown: if (block) { block(NetworkReachabilityStatusUnknown); } break; // 沒有網絡 case AFNetworkReachabilityStatusNotReachable: if (block) { block(NetworkReachabilityStatusNotReachable); } break; // 手機自帶網絡 case AFNetworkReachabilityStatusReachableViaWWAN: if (block) { block(NetworkReachabilityStatusReachableViaWWAN); } break; // WIFI case AFNetworkReachabilityStatusReachableViaWiFi: if (block) { block(NetworkReachabilityStatusReachableViaWiFi); } break; } }]; [netMan startMonitoring];} +(void)stopMonitoring{ AFNetworkReachabilityManager *netMan = [AFNetworkReachabilityManager sharedManager]; [netMan stopMonitoring]; } +(Boolean)JudgeNetisConnect{ NSString *urlstr=WuCheBaseUrl; NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlstr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; if (response!=NULL) { return YES; } return NO; } @end
以上這篇iOS AFNetworking各種功能封裝類代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。