溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

iOS AFNetworking各種功能封裝類代碼

發(fā)布時(shí)間:2020-09-18 17:13:15 來(lái)源:腳本之家 閱讀:234 作者:鍵盤舞者113 欄目:移動(dòng)開(kāi)發(fā)

這個(gè)封裝類包含了GET請(qǐng)求,POST請(qǐng)求,上傳圖片,上傳多張圖片,下載圖片,判斷網(wǎng)絡(luò)是否可用等功能。

#import <Foundation/Foundation.h>
@interface HttpUtil : NSObject

typedef NS_ENUM(NSInteger, NetworkReachabilityStatus) { NetworkReachabilityStatusUnknown   = -1, NetworkReachabilityStatusNotReachable  = 0, NetworkReachabilityStatusReachableViaWWAN = 1, NetworkReachabilityStatusReachableViaWiFi = 2,
};

// GET請(qǐng)求
+ (void)getWithURLString:(NSString *)URLString
    parameters:(id)parameters
     success:(void (^)(id))success
     failure:(void (^)(NSError * error))failure;

// POST請(qǐng)求
+ (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請(qǐng)求 --
+ (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請(qǐng)求 --
+ (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.創(chuàng)建管理者對(duì)象
 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 URLString=[self DownLoadUrlWithParams:URLString WithNSDictionaryParams:parameters];
 NSLog(@"DownLoadFileUrl %@",URLString);
 NSURL *url = [NSURL URLWithString:URLString];
 //3.創(chuàng)建請(qǐng)求對(duì)象
 NSURLRequest *request = [NSURLRequest requestWithURL:url];
 //下載任務(wù)
 NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  if (progress) {
   progress(downloadProgress);
  }
 } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  //  //下載地址
  //  //設(shè)置下載路徑,通過(guò)沙盒獲取緩存地址,最后返回NSURL對(duì)象
  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);
  }
 }];
 //開(kāi)始啟動(dòng)任務(wù)
 [task resume];
}
//因?yàn)橄螺d的方法不能夠直接填寫dict參數(shù)進(jìn)去,所以只有使用這種方法拼接參數(shù)進(jìn)去
+(NSString *)DownLoadUrlWithParams:(NSString*)url WithNSDictionaryParams:(NSDictionary *)params{
 // 初始化參數(shù)變量
 NSString *body=@"";
 // 快速遍歷參數(shù)數(shù)組
 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{ //監(jiān)測(cè)網(wǎng)絡(luò)狀態(tài)
 AFNetworkReachabilityManager *netMan = [AFNetworkReachabilityManager sharedManager];
 [netMan setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  switch (status) {
    // 未知網(wǎng)絡(luò)
   case AFNetworkReachabilityStatusUnknown:
    if (block) {
     block(NetworkReachabilityStatusUnknown);
    }
    break;
    // 沒(méi)有網(wǎng)絡(luò)
   case AFNetworkReachabilityStatusNotReachable:
    if (block) {
     block(NetworkReachabilityStatusNotReachable);
    }
    break;
    // 手機(jī)自帶網(wǎng)絡(luò)
   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各種功能封裝類代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI