LCHttpHelper.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. //
  2. // LCHttpHelper.m
  3. // LiveChat
  4. //
  5. // Created by 张灿 on 2018/4/11.
  6. // Copyright © 2018年 caicai. All rights reserved.
  7. //
  8. #import "LCHttpHelper.h"
  9. #import "YOUPAIXRWalletVC.h"
  10. #import "AppDelegate.h"
  11. #import "LZAlertWindow.h"
  12. #import "UIViewController+TFPresent.h"
  13. #import "YOUPAIXRWalletVC.h"
  14. #import "YOUPAIHRRechargePayWindow.h"
  15. #import "YOUPAIBBMD5.h"
  16. #import <AppTrackingTransparency/AppTrackingTransparency.h>
  17. #import <AdSupport/AdSupport.h>
  18. static NSString *kSignature = @"QY";//@"TF";//@"AS";//@"QY"
  19. static NSString *kChannel = @"22";
  20. @implementation LCHttpHelper
  21. + (AFHTTPSessionManager *)shareManager{
  22. static AFHTTPSessionManager *manager = nil ;//1.声明一个空的静态的单例对象
  23. static dispatch_once_t onceToken; //2.声明一个静态的gcd的单次任务
  24. dispatch_once(&onceToken, ^{ //3.执行gcd单次任务:对对象进行初始化
  25. if (manager == nil) {
  26. manager = [AFHTTPSessionManager manager];
  27. }
  28. });
  29. return manager;
  30. }
  31. + (AFSecurityPolicy *)customSecurityPolicy
  32. {
  33. //先导入证书,找到证书的路径
  34. // NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"httpsRequest" ofType:@"cer"];
  35. // NSData *certData = [NSData dataWithContentsOfFile:cerPath];
  36. //AFSSLPinningModeCertificate 使用证书验证模式
  37. AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  38. // [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  39. //allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
  40. //如果是需要验证自建证书,需要设置为YES
  41. securityPolicy.allowInvalidCertificates = YES;
  42. //validatesDomainName 是否需要验证域名,默认为YES;
  43. //假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
  44. //置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。
  45. //如置为NO,建议自己添加对应域名的校验逻辑。
  46. securityPolicy.validatesDomainName = NO;
  47. // NSSet *set = [[NSSet alloc] initWithObjects:certData, nil];
  48. // securityPolicy.pinnedCertificates = set;
  49. return securityPolicy;
  50. }
  51. + (NSURLSessionDataTask *)requestWithURLString:(NSString *)URLString
  52. parameters:(id)parameters
  53. needToken:(BOOL)needToken
  54. type:(HttpRequestType)type
  55. success:(void (^)(id responseObject))success
  56. failure:(void (^)(NSError *error))failure
  57. {
  58. if([URLString rangeOfString:@"app/config"].location != NSNotFound){
  59. NSLog(@"请求配置接口信息");
  60. }
  61. NSString * urlstr=[NSString stringWithFormat:@"%@%@",[LCSaveData getBaseURL]?[LCSaveData getBaseURL]:BaseURL,URLString];
  62. // NSLog(@"请求域名域名域名:%@",urlstr);
  63. NSString* encodedStr =[urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  64. NSString *bdId = [[NSBundle mainBundle] bundleIdentifier];
  65. NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)parameters];
  66. // NSLog(@"%@",parms);
  67. AFHTTPSessionManager *manager = [self shareManager];
  68. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"image/jpeg",@"image/gif", nil];
  69. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  70. [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
  71. manager.requestSerializer.timeoutInterval = 10.f;//超时时长
  72. [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
  73. //
  74. [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"source-id"];
  75. [manager.requestSerializer setValue:bdId forHTTPHeaderField:@"package-name"];
  76. [manager.requestSerializer setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"ver-code"];
  77. // if ([LCSaveData getWhiteVersion]) {
  78. // color = @"vqu-white";
  79. // }else{
  80. // color = @"vqu-black";
  81. // }
  82. // [manager.requestSerializer setValue:color forHTTPHeaderField:@"theme"];
  83. //企业签名还是TF签名
  84. [manager.requestSerializer setValue:kSignature forHTTPHeaderField:@"signature"];
  85. if (needToken) {
  86. //NSLog(@"getTokenString = %@",[LCSaveData getTokenString]);
  87. if ([LCSaveData getTokenString] != nil) {
  88. NSString* tokenStr = [NSString stringWithFormat:@"%@",[LCSaveData getTokenString]];
  89. [manager.requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
  90. }else{
  91. [[NSNotificationCenter defaultCenter] postNotificationName:@"AbnormalLogout" object:nil userInfo:nil];
  92. //[ZCHUDHelper showTitle:@"登录状态过期,需重新登录" showtime:4];
  93. [LCTools changeRootToLogin];
  94. }
  95. }
  96. [manager.requestSerializer setValue:[LCTools getUUIDString] forHTTPHeaderField:@"oaid"];
  97. //机型
  98. [manager.requestSerializer setValue:[LCTools iphoneType] forHTTPHeaderField:@"phone-brand"];
  99. [manager.requestSerializer setValue:[[UIApplication sharedApplication] appVersion] forHTTPHeaderField:@"version"];
  100. NSString *chancelCode = [LCTools getchannelCode];
  101. if (chancelCode.length<=0) {
  102. [manager.requestSerializer setValue:kChannel forHTTPHeaderField:@"channel"];//渠道号
  103. }else{
  104. [manager.requestSerializer setValue:[LCTools getchannelCode] forHTTPHeaderField:@"channel"];//渠道号
  105. }
  106. //modify by leo
  107. [manager.requestSerializer setValue:[LCTools getUUIDString] forHTTPHeaderField:@"uuid"];
  108. [manager.requestSerializer setValue:[LCTools getNetworkType] forHTTPHeaderField:@"network-status"];
  109. [self md5Parms:parms andManager:manager];//参数md5加密
  110. //HTTPS SSL的验证,在此处调用上面的代码,给这个证书验证;
  111. [manager setSecurityPolicy:[self customSecurityPolicy]];
  112. LCLog(@"%@",manager.requestSerializer.HTTPRequestHeaders);
  113. switch (type) {
  114. case HttpRequestTypeGet:
  115. {
  116. return [manager GET:encodedStr parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  117. if (success) {
  118. responseObject = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  119. NSDictionary* dict = [LPSecureData getDictWithSecureString:(NSString*)responseObject];
  120. YMLog(@"**************************************************\n[✅]url:%@\n参数:%@ \n返回值:%@",encodedStr,parms,dict);
  121. success((id)dict);
  122. [self handelSussess:dict];
  123. }
  124. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  125. NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
  126. NSData *errorData = [error.userInfo valueForKey:AFNetworkingOperationFailingURLResponseDataErrorKey];
  127. NSDictionary *erroInfo = errorData ? [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingMutableContainers error:nil] : @{};
  128. YMLog(@"**************************************************\n[❌]url:%@\n参数:%@ \n返回值:%@",encodedStr,parms,OCDictionaryIsEmpty(erroInfo) ? error : erroInfo);
  129. YMLog(@"\n#####请求错误Code#####\nstatusCode = %ld\n####################\ntask = %@\n", (long)responses.statusCode,task.currentRequest);
  130. [ZCHUDHelper showTitle:@"请检查网络连接"];
  131. if (failure) {
  132. failure(error);
  133. }
  134. }];
  135. }
  136. break;
  137. case HttpRequestTypePost:
  138. {
  139. return [manager POST:encodedStr parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  140. if (success) {
  141. // success(responseObject);
  142. // NSDictionary* dict = (NSDictionary*)responseObject;
  143. responseObject = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  144. NSString* string = [[NSString stringWithFormat:@"%@",responseObject] stringByReplacingOccurrencesOfString:@"签名验证通过\n" withString:@""];
  145. NSDictionary* dict = [LPSecureData getDictWithSecureString:(NSString*)string];
  146. YMLog(@"**************************************************\n[✅]url:%@\n参数:%@ \n返回值:%@\n原始值:%@",encodedStr,parms,dict,responseObject);
  147. success((id)dict);
  148. [self handelSussess:dict];
  149. }
  150. // [manager.session finishTasksAndInvalidate];
  151. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  152. NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
  153. NSData *errorData = [error.userInfo valueForKey:AFNetworkingOperationFailingURLResponseDataErrorKey];
  154. NSDictionary *erroInfo = errorData ? [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingMutableContainers error:nil] : @{};
  155. YMLog(@"**************************************************\n[❌]url:%@\n参数:%@ \n返回值:%@",encodedStr,parms,OCDictionaryIsEmpty(erroInfo) ? error : erroInfo);
  156. YMLog(@"\n#####请求错误Code#####\nstatusCode = %ld\n####################\ntask = %@\n", (long)responses.statusCode,task.currentRequest);
  157. #ifdef checkEnviTest
  158. [ZCHUDHelper showTitle:error.description showtime:10.0];
  159. #endif
  160. if (failure) {
  161. failure(error);
  162. }
  163. // [manager.session finishTasksAndInvalidate];
  164. }];
  165. }
  166. break;
  167. }
  168. }
  169. + (void)postImageArrayToSeverWithURLString:(NSString *)URLString
  170. imgArray:(NSArray<UIImage*> *)imgArray
  171. imgNameArray:(NSArray<NSString*>*)imgNameArray
  172. parmeters:(id)parmeters
  173. needToken:(BOOL)needToken
  174. success:(void (^)(id responseObject))success
  175. failure:(void (^)(NSError *error))failure{
  176. if([URLString rangeOfString:@"app/config"].location != NSNotFound){
  177. NSLog(@"请求配置接口信息");
  178. }
  179. NSString * urlstr=[NSString stringWithFormat:@"%@%@",[LCSaveData getBaseURL]?[LCSaveData getBaseURL]:BaseURL,URLString];
  180. NSString *encodedStr =[urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  181. NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)parmeters];
  182. AFHTTPSessionManager *manager = [self shareManager];
  183. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"image/jpeg",@"image/gif",@"multipart/form-data",nil];
  184. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  185. [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
  186. manager.requestSerializer.timeoutInterval = 600.f;//超时时长
  187. [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
  188. [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"source-id"];
  189. [manager.requestSerializer setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"ver-code"];
  190. //企业签名还是TF签名 QY
  191. [manager.requestSerializer setValue:kSignature forHTTPHeaderField:@"signature"];
  192. if (needToken) {
  193. NSString* tokenStr = [NSString stringWithFormat:@"%@",[LCSaveData getTokenString]];
  194. [manager.requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
  195. }
  196. //机型
  197. [manager.requestSerializer setValue:[LCTools iphoneType] forHTTPHeaderField:@"phone-brand"];
  198. [manager.requestSerializer setValue:[[UIApplication sharedApplication] appVersion] forHTTPHeaderField:@"version"];
  199. NSString *chancelCode = [LCTools getchannelCode];
  200. if (chancelCode.length<=0) {
  201. [manager.requestSerializer setValue:kChannel forHTTPHeaderField:@"channel"];//渠道号
  202. }else{
  203. [manager.requestSerializer setValue:[LCTools getchannelCode] forHTTPHeaderField:@"channel"];//渠道号
  204. }
  205. [manager.requestSerializer setValue:[LCTools getUUIDString] forHTTPHeaderField:@"uuid"];
  206. [manager.requestSerializer setValue:[LCTools getNetworkType] forHTTPHeaderField:@"network-status"];
  207. [self md5Parms:parms andManager:manager];//参数md5加密
  208. //HTTPS SSL的验证,在此处调用上面的代码,给这个证书验证;
  209. [manager setSecurityPolicy:[self customSecurityPolicy]];
  210. [manager POST:encodedStr parameters:parms constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  211. for (int i =0; i<imgArray.count; i++) {
  212. NSData *imageData = [UIImage zipNSDataWithImage:imgArray[i] maxFileSize:1024*1024];
  213. [formData appendPartWithFileData:imageData name:imgNameArray[i] fileName:@"xxxx.jpg" mimeType:@"image/jpeg"];
  214. }
  215. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  216. if (success) {
  217. responseObject = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  218. NSDictionary* dict = [LPSecureData getDictWithSecureString:(NSString*)responseObject];
  219. YMLog(@"**************************************************\n[✅]url:%@\n参数:%@ \n返回值:%@",encodedStr,parms,dict);
  220. success((id)dict);
  221. [self handelSussess:dict];
  222. }
  223. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  224. NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
  225. NSData *errorData = [error.userInfo valueForKey:AFNetworkingOperationFailingURLResponseDataErrorKey];
  226. NSDictionary *erroInfo = errorData ? [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingMutableContainers error:nil] : @{};
  227. YMLog(@"**************************************************\n[❌]url:%@\n参数:%@ \n返回值:%@",encodedStr,parms,OCDictionaryIsEmpty(erroInfo) ? error : erroInfo);
  228. YMLog(@"\n#####请求错误Code#####\nstatusCode = %ld\n####################\ntask = %@\n", (long)responses.statusCode,task.currentRequest);
  229. #ifdef checkEnviTest
  230. [ZCHUDHelper showTitle:error.description showtime:10.0];
  231. #endif
  232. if (failure) {
  233. failure(error);
  234. }
  235. }];
  236. }
  237. + (void)handelSussess:(NSDictionary*)dict{
  238. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  239. NSString* msg = [dict objectForKey:@"message"];
  240. if (code==0) {
  241. }else if(code==1001){
  242. [[NSNotificationCenter defaultCenter] postNotificationName:@"AbnormalLogout" object:nil userInfo:nil];
  243. //[ZCHUDHelper showTitle:@"登录状态过期,需重新登录"];
  244. [LCTools changeRootToLogin];
  245. }else if(code==1002){
  246. [ZCHUDHelper showTitle:@"您的可用余额不足"];
  247. // LZAlertAction *cancelAction = [LZAlertAction actionWithTitle:@"舍不得" handler:^(LZAlertAction *action) {
  248. //
  249. // }];
  250. // cancelAction.cornerRadius = 24.0f;
  251. // cancelAction.bgColor = HexColorFromRGB(0x9F9DA5);
  252. // LZAlertAction *confimAction = [LZAlertAction actionWithTitle:@"去充值" handler:^(LZAlertAction *action) {
  253. [[NSNotificationCenter defaultCenter] postNotificationName:@"InsufficientBalanceNotice" object:nil userInfo:nil];
  254. // YOUPAIHRRechargePayWindow *payWindow = [YOUPAIHRRechargePayWindow new];
  255. // payWindow.isTouchDismiss = NO;
  256. // [kAppDelegate.window.rootViewController TFPresentVC:payWindow completion:^{
  257. //
  258. // }];
  259. YMAccountBalanceViewModel *accountBalanceVM = [[YMAccountBalanceViewModel alloc]initWithParams:@{
  260. ParamsId:@([[LCSaveModel getUserModel].youpaipuserinfo.youpaipuser_id intValue])
  261. }];
  262. YMAccountBalanceRechargePopupView *customView = [[YMAccountBalanceRechargePopupView alloc]init];
  263. [customView ym_bindViewModel:accountBalanceVM];
  264. YMPopupView *popupView = [YMPopupView initWithCustomView:customView parentView:nil popStyle:YMPopupStyleSmoothFromBottom dismissStyle:YMDismissStyleSmoothToBottom];
  265. popupView.priority = 999;
  266. popupView.cornerRadius = adapt(10);
  267. popupView.rectCorners = UIRectCornerTopLeft|UIRectCornerTopRight;
  268. popupView.positionStyle = YMPositionStyleBottom;
  269. popupView.isClickBgDismiss = YES;
  270. popupView.isHideBg = NO;
  271. popupView.bgAlpha = 0.5;
  272. [popupView pop];
  273. @weakify(popupView)
  274. customView.dismissBlock = ^{
  275. @strongify(popupView)
  276. [popupView dismissWithStyle:YMDismissStyleSmoothToBottom duration:2.0];
  277. };
  278. // }];
  279. // confimAction.cornerRadius = 24.0f;
  280. // confimAction.bgColor = [UIColor colorWithPatternImage:[LCTools ColorImage:CGSizeMake((KScreenWidth - 105.0f) / 2.0f, 48.0f) FromColors:@[ZYGradientOneColor,ZYGradientTwoColor] ByGradientType:GradientLeftToRight]];
  281. // LZAlertWindow *alert = [LZAlertWindow alertWithTitle:@"提示" content:@"您的可用余额不足,去充值" action:@[cancelAction,confimAction]];
  282. // alert.contentTextAlignment = NSTextAlignmentCenter;
  283. // [kAppDelegate.window.rootViewController TFPresentVC:alert completion:^{}];
  284. }else if(code==1003){
  285. [ZCHUDHelper showTitle:@"您的可用余额不足"];
  286. // LZAlertAction *cancelAction = [LZAlertAction actionWithTitle:@"舍不得" handler:^(LZAlertAction *action) {
  287. //
  288. // }];
  289. // cancelAction.cornerRadius = 24.0f;
  290. // cancelAction.bgColor = HexColorFromRGB(0x9F9DA5);
  291. // LZAlertAction *confimAction = [LZAlertAction actionWithTitle:@"去充值" handler:^(LZAlertAction *action) {
  292. [[NSNotificationCenter defaultCenter] postNotificationName:@"InsufficientBalanceNotice" object:nil userInfo:nil];
  293. // YOUPAIHRRechargePayWindow *payWindow = [YOUPAIHRRechargePayWindow new];
  294. // payWindow.isTouchDismiss = NO;
  295. // [kAppDelegate.window.rootViewController TFPresentVC:payWindow completion:^{
  296. //
  297. // }];
  298. YMAccountBalanceViewModel *accountBalanceVM = [[YMAccountBalanceViewModel alloc]initWithParams:@{
  299. ParamsId:@([[LCSaveModel getUserModel].youpaipuserinfo.youpaipuser_id intValue])
  300. }];
  301. YMAccountBalanceRechargePopupView *customView = [[YMAccountBalanceRechargePopupView alloc]init];
  302. [customView ym_bindViewModel:accountBalanceVM];
  303. YMPopupView *popupView = [YMPopupView initWithCustomView:customView parentView:nil popStyle:YMPopupStyleSmoothFromBottom dismissStyle:YMDismissStyleSmoothToBottom];
  304. popupView.priority = 999;
  305. popupView.cornerRadius = adapt(10);
  306. popupView.rectCorners = UIRectCornerTopLeft|UIRectCornerTopRight;
  307. popupView.positionStyle = YMPositionStyleBottom;
  308. popupView.isClickBgDismiss = YES;
  309. popupView.isHideBg = NO;
  310. popupView.bgAlpha = 0.5;
  311. [popupView pop];
  312. @weakify(popupView)
  313. customView.dismissBlock = ^{
  314. @strongify(popupView)
  315. [popupView dismissWithStyle:YMDismissStyleSmoothToBottom duration:2.0];
  316. };
  317. // YOUPAIXRWalletVC* coinRecharge = [[YOUPAIXRWalletVC alloc]init];
  318. // [[ZCUtils getCurrentVC].navigationController pushViewController:coinRecharge animated:YES];
  319. // }];
  320. // confimAction.cornerRadius = 24.0f;
  321. // confimAction.bgColor = [UIColor colorWithPatternImage:[LCTools ColorImage:CGSizeMake((KScreenWidth - 105.0f) / 2.0f, 48.0f) FromColors:@[ZYGradientOneColor,ZYGradientTwoColor] ByGradientType:GradientLeftToRight]];
  322. // LZAlertWindow *alert = [LZAlertWindow alertWithTitle:@"提示" content:@"您的钻石数量不足,去购买" action:@[cancelAction,confimAction]];
  323. // alert.contentTextAlignment = NSTextAlignmentCenter;
  324. // [kAppDelegate.window.rootViewController TFPresentVC:alert completion:^{}];
  325. }else{
  326. if ([msg isKindOfClass:[NSString class]]) {
  327. if(![msg isEqualToString:@""]){
  328. if (code>0) {
  329. [ZCHUDHelper showTitle:msg showtime:4.0];
  330. }else{
  331. [ZCHUDHelper showTitle:msg];
  332. }
  333. }
  334. }
  335. }
  336. }
  337. +(void)md5Parms:(NSDictionary *)parms andManager:(AFHTTPSessionManager *)manager
  338. {
  339. NSString *timeSp = [NSString stringWithFormat:@"%ld",[[LCTools getCurrentMillisecondTimestamp] integerValue] + [LCSaveData getTimeDifference]];//时间戳
  340. NSString *random = [LCTools randomNumberWithLength:6];
  341. NSArray *sortKeys = [[parms allKeys] sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  342. return [obj1 compare: obj2 options:NSNumericSearch];
  343. }];
  344. // NSLog(@"sortKeys = %@",sortKeys);
  345. NSString *string;
  346. for (int i = 0; i < sortKeys.count; i++)
  347. {
  348. if (i == 0) {
  349. string = [NSString stringWithFormat:@"%@%@", sortKeys[i], parms[sortKeys[i]]];
  350. }else{
  351. string = [NSString stringWithFormat:@"%@%@%@",string,sortKeys[i], parms[sortKeys[i]]];
  352. }
  353. }
  354. // NSLog(@"string = %@",parms);
  355. //
  356. // NSLog(@"string = %@",string);
  357. NSString *signStr;
  358. if (sortKeys.count == 0) {
  359. signStr = [NSString stringWithFormat:@"%@%@%@%@",kYanQianKey,timeSp,random,[LCTools getUUIDString]];
  360. }else{
  361. signStr = [NSString stringWithFormat:@"%@%@%@%@%@",string,kYanQianKey,timeSp,random,[LCTools getUUIDString]];
  362. }
  363. NSLog(@"str = %@",signStr);
  364. // if ([LCSaveData getWhiteVersion]) {
  365. // [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"package-type"];//是否为baibao
  366. // }else{
  367. // [manager.requestSerializer setValue:@"0" forHTTPHeaderField:@"package-type"];//是否为baibao
  368. // }
  369. //
  370. [manager.requestSerializer setValue:[@([LCSaveData getWhiteVersion]) stringValue] forHTTPHeaderField:@"package-type"];//是否为baibao 1是
  371. [manager.requestSerializer setValue:timeSp forHTTPHeaderField:@"timestamp"];
  372. [manager.requestSerializer setValue:random forHTTPHeaderField:@"random"];
  373. [manager.requestSerializer setValue:[YOUPAIBBMD5 youpaifmd5To32bit:signStr] forHTTPHeaderField:@"sign"];
  374. if ([LCSaveData getWhiteVersion]) {
  375. [manager.requestSerializer setValue:@"vqu-white" forHTTPHeaderField:@"theme"];
  376. }else{
  377. [manager.requestSerializer setValue:@"vqu-white" forHTTPHeaderField:@"theme"];
  378. }
  379. if (@available(iOS 14, *)) {
  380. // iOS14及以上版本需要先请求权限
  381. [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
  382. // 获取到权限后,依然使用老方法获取idfa
  383. if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
  384. NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
  385. [manager.requestSerializer setValue:idfa forHTTPHeaderField:@"idfa"];
  386. NSLog(@"%@",idfa);
  387. } else {
  388. NSLog(@"请在设置-隐私-跟踪中允许App请求跟踪");
  389. }
  390. }];
  391. } else {
  392. // iOS14以下版本依然使用老方法
  393. // 判断在设置-隐私里用户是否打开了广告跟踪
  394. if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
  395. NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
  396. [manager.requestSerializer setValue:idfa forHTTPHeaderField:@"idfa"];
  397. NSLog(@"%@",idfa);
  398. } else {
  399. NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
  400. }
  401. }
  402. }
  403. @end