ZYLNetworkClient.m 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. //
  2. // ZYLNetworkClient.m
  3. // NetworkLayerBuild
  4. //
  5. // Created by 翟玉磊 on 2017/8/31.
  6. // Copyright © 2017年 翟玉磊. All rights reserved.
  7. //
  8. #import "ZYLNetworkClient.h"
  9. #import "ZYLURLRequestGenerator.h"
  10. #import "AFNetworking.h"
  11. @interface ZYLNetworkClient ()
  12. @property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
  13. @property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSURLSessionTask *> *dispatchTable;
  14. @property (nonatomic, assign) CGFloat totaltaskCount;
  15. @property (nonatomic, assign) CGFloat errorTaskCount;
  16. @end
  17. @implementation ZYLNetworkClient
  18. static dispatch_semaphore_t lock;
  19. + (instancetype)sharedInstance {
  20. static ZYLNetworkClient *sharedInstance;
  21. static dispatch_once_t onceToken;
  22. dispatch_once(&onceToken, ^{
  23. lock = dispatch_semaphore_create(1);
  24. sharedInstance = [[super allocWithZone:NULL] init];
  25. });
  26. return sharedInstance;
  27. }
  28. + (instancetype)allocWithZone:(struct _NSZone *)zone {
  29. return [self sharedInstance];
  30. }
  31. - (instancetype)init {
  32. if (self = [super init]) {
  33. self.dispatchTable = [NSMutableDictionary dictionary];
  34. self.totaltaskCount = self.errorTaskCount = 0;
  35. self.sessionManager = [AFHTTPSessionManager manager];
  36. // if (IS_DEBUG) {
  37. // 测试不需要验证
  38. // self.sessionManager.securityPolicy.validatesDomainName = NO; //是否验证域名证书的CN字段
  39. // self.sessionManager.securityPolicy.allowInvalidCertificates = YES; //是否信任服务器无效或过期的SSL证书
  40. // }else {
  41. // // 验证本地证书
  42. // AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:[AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]]];
  43. // //是否验证域名证书的CN字段
  44. // securityPolicy.validatesDomainName = NO;
  45. // //是否信任服务器无效或过期的SSL证书
  46. // securityPolicy.allowInvalidCertificates = YES;
  47. // self.sessionManager.securityPolicy = securityPolicy;
  48. // }
  49. self.sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
  50. NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:self.sessionManager.responseSerializer.acceptableContentTypes];
  51. [acceptableContentTypes addObject:@"text/html"];
  52. [acceptableContentTypes addObject:@"text/plain"];
  53. self.sessionManager.responseSerializer.acceptableContentTypes = [acceptableContentTypes copy];
  54. }
  55. return self;
  56. }
  57. #pragma mark - Interface
  58. - (NSNumber *)dispathTask:(NSURLSessionTask *)task {
  59. if (task == nil) {
  60. return @-1;
  61. }
  62. dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  63. self.totaltaskCount += 1;
  64. [self.dispatchTable setObject:task forKey:@(task.taskIdentifier)];
  65. dispatch_semaphore_signal(lock);
  66. [task resume];
  67. return @(task.taskIdentifier);
  68. }
  69. - (NSNumber *)dispatchTaskWithUrlPath:(NSString *)urlPath useHttps:(BOOL)useHttps requestType:(ZYLNetworkRequestType)requestType params:(NSDictionary *)params header:(NSDictionary *)header completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {
  70. return [self dispathTask:[self dataTaskWithUrlPath:urlPath useHttps:useHttps requestType:requestType params:params header:header completionHandler:completionHandler]];
  71. }
  72. - (NSURLSessionDataTask *)dataTaskWithUrlPath:(NSString *)urlPath useHttps:(BOOL)useHttps requestType:(ZYLNetworkRequestType)requestType params:(NSDictionary *)params header:(NSDictionary *)header completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {
  73. NSString *method = (requestType == ZYLNetworkRequestTypeGet ? @"GET" : @"POST");
  74. NSMutableURLRequest *requset = [[ZYLURLRequestGenerator sharedInstance] generateRequestWithUrlPath:urlPath useHttps:useHttps method:method params:params header:header];
  75. //打印header
  76. // NSLog(@"requset.allHTTPHeaderFields:%@", requset.allHTTPHeaderFields);
  77. NSMutableArray *taskIdentifier = [NSMutableArray arrayWithObject:@-1];
  78. __block NSURLSessionDataTask *task = nil;
  79. task = [self.sessionManager dataTaskWithRequest:requset uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  80. NSString *temp = [NSString stringWithFormat:@"\n---urlPath:%@\n---responseObject:%@\n---error:%@",urlPath,responseObject, error];
  81. NSLog(@"%@",temp);
  82. // HDNormalLog(temp);
  83. dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  84. [self checkSeriveWithTaskError:error];
  85. [self.dispatchTable removeObjectForKey:taskIdentifier.firstObject];
  86. dispatch_semaphore_signal(lock);
  87. completionHandler ? completionHandler(response, responseObject, error) : nil;
  88. }];
  89. taskIdentifier[0] = @(task.taskIdentifier);
  90. return task;
  91. }
  92. - (NSNumber *)uploadDataWithUrlPath:(NSString *)urlPath useHttps:(BOOL)useHttps contents:(NSArray<ZYLUploadFile *> *)contents params:(NSDictionary *)params header:(NSDictionary *)header progressHandler:(void (^)(NSProgress *))progressHandler completionHandler:(void (^)(NSURLResponse *, id, NSError *))comletionHandler {
  93. NSMutableURLRequest *request = [[ZYLURLRequestGenerator sharedInstance] generateUploadRequestWithUrlPath:urlPath useHttps:useHttps params:params contents:contents header:header];
  94. NSMutableArray *taskIdentifier = [NSMutableArray arrayWithObject:@-1];
  95. NSURLSessionDataTask *task = [self.sessionManager uploadTaskWithStreamedRequest:request progress:progressHandler completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  96. NSString *temp = [NSString stringWithFormat:@"\n---urlPath:%@response:%@---\nresponseObject:%@\n---error:%@", urlPath,response, responseObject, error];
  97. NSLog(@"%@",temp);
  98. // HDNormalLog(temp);
  99. dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  100. [self.dispatchTable removeObjectForKey:taskIdentifier.firstObject];
  101. dispatch_semaphore_signal(lock);
  102. comletionHandler ? comletionHandler(response, responseObject, error) : nil;
  103. }];
  104. taskIdentifier[0] = @(task.taskIdentifier);
  105. return [self dispathTask:task];
  106. }
  107. - (void)cancelAllTask {
  108. for (NSURLSessionTask *task in self.dispatchTable.allValues) {
  109. [task cancel];
  110. }
  111. dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  112. [self.dispatchTable removeAllObjects];
  113. dispatch_semaphore_signal(lock);
  114. }
  115. - (void)cancelTaskWithTaskIdentifier:(NSNumber *)taskIdentifier {
  116. [self.dispatchTable[taskIdentifier] cancel];
  117. dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  118. [self.dispatchTable removeObjectForKey:taskIdentifier];
  119. dispatch_semaphore_signal(lock);
  120. }
  121. ///获取请求中的task任务(请求完成后自动移除task任务)
  122. - (NSURLSessionDataTask *)getTask:(NSNumber *)taskIdentifier{
  123. NSURLSessionDataTask *task = (NSURLSessionDataTask *)[self.dispatchTable objectForKey:taskIdentifier];
  124. return task;
  125. }
  126. #pragma mark - Notification
  127. - (void)didReceivedSwitchSeriveNotification:(NSNotification *)notification {
  128. dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  129. self.totaltaskCount = self.errorTaskCount = 0;
  130. dispatch_semaphore_signal(lock);
  131. }
  132. #pragma mark - Utils
  133. - (void)checkSeriveWithTaskError:(NSError *)error {
  134. if ([ZYLAPPContext sharedInstance].isReachable) {
  135. switch (error.code) {
  136. case NSURLErrorUnknown:
  137. case NSURLErrorTimedOut:
  138. case NSURLErrorCannotConnectToHost: {
  139. self.errorTaskCount += 1;
  140. }
  141. default:
  142. break;
  143. }
  144. }
  145. }
  146. @end