口袋优选

ZmzAFNetworking.m 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //
  2. // ZmzAFNetworking.m
  3. // afCach
  4. //
  5. // Created by CiHon-IOS2 on 16/9/29.
  6. // Copyright © 2016年 walkingzmz. All rights reserved.
  7. // 30岁前一定有的心态
  8. // 事业永远第一;别把钱看得太重;学会体谅父母;交上好朋友;不要沉迷于任何东西;年轻没有失败;不要轻易崇拜或者鄙视一个人;要有责任心;外貌并不重要;学会保护身体;别觉得一事无成;认真工作;认真对待感情;留一点童心。
  9. #import "ZmzAFNetworking.h"
  10. #import "YBMD5.h"
  11. #import <objc/runtime.h>
  12. #import "YBCacheConstant.h"
  13. #import <AdSupport/AdSupport.h>
  14. /**
  15. * 存放 网络请求的线程
  16. */
  17. static NSMutableArray *sg_requestTasks;
  18. static NSString *const MAIN_URLL = BaseURL;
  19. @implementation YBCache
  20. @end
  21. static char *NSErrorStatusCodeKey = "NSErrorStatusCodeKey";
  22. @implementation NSError (YBHttp)
  23. - (void)setStatusCode:(NSInteger)statusCode
  24. {
  25. objc_setAssociatedObject(self, NSErrorStatusCodeKey, @(statusCode), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  26. }
  27. - (NSInteger)statusCode
  28. {
  29. return [objc_getAssociatedObject(self, NSErrorStatusCodeKey) integerValue];
  30. }
  31. @end
  32. @interface ZmzAFNetworking()
  33. @property (nonatomic, strong)AFHTTPSessionManager *manager;
  34. @property (nonatomic, assign, getter=isConnected) BOOL connected;/**<网络是否连接*/
  35. @property (nonatomic, retain) NSURLSessionTask *task;
  36. @end
  37. @implementation ZmzAFNetworking
  38. //-(AFHTTPSessionManager *)manager{
  39. // static AFHTTPSessionManager *rmanager = nil;
  40. // static dispatch_once_t onceToken;
  41. // dispatch_once(&onceToken, ^{
  42. // rmanager = [AFHTTPSessionManager manager];
  43. //
  44. // rmanager.responseSerializer = [AFJSONResponseSerializer serializer];
  45. // rmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/jpg",@"application/x-javascript",@"keep-alive", nil];
  46. // // 设置超时时间
  47. // [rmanager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
  48. // rmanager.requestSerializer.timeoutInterval = 60.f;
  49. // [rmanager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
  50. //
  51. // });
  52. // return rmanager;
  53. //}
  54. - (AFHTTPSessionManager *)manager {
  55. // 1.创建请求管理者
  56. AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
  57. mgr.requestSerializer = [AFJSONRequestSerializer serializer]; // 解析为data
  58. mgr.responseSerializer = [AFJSONResponseSerializer serializer];
  59. mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/jpg",@"application/x-javascript",@"keep-alive", nil];
  60. mgr.requestSerializer.timeoutInterval = 15;
  61. NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
  62. NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
  63. [mgr.requestSerializer setValue:app_Version forHTTPHeaderField:@"version"];
  64. [mgr.requestSerializer setValue:Channel_id forHTTPHeaderField:@"source"];
  65. [mgr.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"];
  66. NSString *deviceUUID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
  67. NSString *uuid = [NSString stringWithFormat:@"I-%@",deviceUUID];
  68. [mgr.requestSerializer setValue:uuid forHTTPHeaderField:@"idfa"];
  69. if ([AccountTool isLogin]) {
  70. NSString *token = [AccountTool account].token;
  71. [mgr.requestSerializer setValue:token forHTTPHeaderField:@"token"];
  72. }
  73. // jcytesttoken
  74. NSString *sex = [[NSUserDefaults standardUserDefaults] objectForKey:UserSexKey];
  75. [mgr.requestSerializer setValue:sex forHTTPHeaderField:@"sex"];
  76. return mgr;
  77. }
  78. - (BOOL)isConnected {
  79. struct sockaddr zeroAddress;
  80. bzero(&zeroAddress, sizeof(zeroAddress));
  81. zeroAddress.sa_len = sizeof(zeroAddress);
  82. zeroAddress.sa_family = AF_INET;
  83. SCNetworkReachabilityRef defaultRouteReachability =
  84. SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
  85. SCNetworkReachabilityFlags flags;
  86. BOOL didRetrieveFlags =
  87. SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
  88. CFRelease(defaultRouteReachability);
  89. if (!didRetrieveFlags) {
  90. printf("Error. Count not recover network reachability flags\n");
  91. return NO;
  92. }
  93. BOOL isReachable = flags & kSCNetworkFlagsReachable;
  94. BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
  95. return (isReachable && !needsConnection) ? YES : NO;
  96. }
  97. -(void)requsetWithPath:(NSString *)path withParams:(NSDictionary *)params withCacheType:(YBCacheType)cacheType withRequestType:(NetworkRequestType)type withResult:(ZmzBlock)resultBlock{
  98. if (!self.isConnected) {
  99. NSLog(@"没有网络,建议在手机设置中打开网络");
  100. // return;
  101. }
  102. switch (type) {
  103. case NetworkGetType:
  104. {
  105. YBCache *cache = [self getCache:cacheType url:path params:params withResult:resultBlock];
  106. NSString *fileName = cache.fileName;
  107. if (cache.result) return;
  108. [self.manager GET:path parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
  109. // YBLog(@"---------%lld", downloadProgress.totalUnitCount);
  110. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  111. if (resultBlock) {
  112. if ([responseObject[@"errno"] isEqualToString:@"0"]) {
  113. //缓存数据
  114. NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
  115. [YBCacheTool cacheForData:data fileName:fileName];
  116. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  117. }else {
  118. //errno不是0则返回错误
  119. NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
  120. NSString *desc = NSLocalizedString(@"Unable to…", @"");
  121. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
  122. NSInteger code = [responseObject[@"errno"] integerValue];
  123. NSError *error = [NSError errorWithDomain:domain
  124. code:code
  125. userInfo:userInfo];
  126. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  127. }
  128. }
  129. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  130. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  131. }];
  132. }
  133. break;
  134. case NetworkPostType:
  135. {
  136. NSString *cutPath = [NSString stringWithFormat:@"%@",path];
  137. /*
  138. [self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
  139. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  140. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  141. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  142. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  143. }];
  144. */
  145. //缓存数据的文件名 data
  146. YBCache *cache = [self getCache:cacheType url:cutPath params:params withResult:resultBlock];
  147. NSString *fileName = cache.fileName;
  148. if (cache.result) return;
  149. [self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
  150. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  151. if (resultBlock) {
  152. if ([responseObject[@"errno"] isEqualToString:@"0"]) {
  153. //缓存数据
  154. NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
  155. [YBCacheTool cacheForData:data fileName:fileName];
  156. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  157. }else {
  158. //errno不是0则返回错误
  159. NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
  160. NSString *desc = NSLocalizedString(@"Unable to…", @"");
  161. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
  162. NSInteger code = [responseObject[@"errno"] integerValue];
  163. NSError *error = [NSError errorWithDomain:domain
  164. code:code
  165. userInfo:userInfo];
  166. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  167. }
  168. }
  169. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  170. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  171. }];
  172. }
  173. break;
  174. default:
  175. break;
  176. }
  177. }
  178. -(void)downloadWithrequest:(NSString *)urlString downloadpath:(NSString *)downloadpath downloadblock:(ZmzDownBlock)downloadblock{
  179. if (!self.connected) {
  180. return;
  181. }
  182. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
  183. self.task = [self.manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
  184. NSURL *desturl = [NSURL fileURLWithPath:downloadpath];
  185. return desturl;
  186. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
  187. downloadblock(response,filePath,error);
  188. }];
  189. [self.task resume];
  190. }
  191. - (void)handleRequestResultWithDataTask:(NSURLSessionDataTask *)task
  192. responseObject:(id)responseObject
  193. error:(NSError *)error
  194. resultBlock:(ZmzBlock)resultBlock {
  195. //do something here...
  196. // NSLog(@"%@==-==%@",responseObject,error);
  197. if(resultBlock) {
  198. resultBlock(responseObject,error,NO);
  199. }
  200. }
  201. - (NSURLSessionTask *)uploadImageWithUrl:(NSString *)url
  202. WithParams:(NSDictionary*)params
  203. image:(NSData *)imageData
  204. filename:(NSString *)name
  205. mimeType:(NSString *)mimetype
  206. completion:(requestSuccessBlock)completion
  207. errorBlock:(requestFailureBlock)errorBlock{
  208. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  209. AFHTTPSessionManager *manager = [self manager];
  210. NSURLSessionTask *operation = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  211. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  212. formatter.dateFormat = @"yyyyMMddHHmmss";
  213. NSString *str = [formatter stringFromDate:[NSDate date]];
  214. NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
  215. // 上传图片,以文件流的格式
  216. [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:mimetype];
  217. } progress:^(NSProgress * _Nonnull uploadProgress) {
  218. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  219. completion(responseObject);
  220. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  221. errorBlock(error);
  222. }];
  223. return operation;
  224. }
  225. - (NSURLSessionTask *)uploadVedioWithUrl:(NSString *)url
  226. WithParams:(NSDictionary*)params
  227. image:(NSData *)vedioData
  228. filename:(NSString *)name
  229. mimeType:(NSString *)mimetype
  230. completion:(requestSuccessBlock)completion
  231. errorBlock:(requestFailureBlock)errorBlock{
  232. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  233. AFHTTPSessionManager *manager = [self manager];
  234. NSURLSessionTask *operation = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  235. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  236. formatter.dateFormat = @"yyyyMMddHHmmss";
  237. NSString *str = [formatter stringFromDate:[NSDate date]];
  238. NSString *fileName = [NSString stringWithFormat:@"%@.mp4",str];
  239. [formData appendPartWithFileData:vedioData name:name fileName:fileName mimeType:mimetype];
  240. } progress:^(NSProgress * _Nonnull uploadProgress) {
  241. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  242. completion(responseObject);
  243. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  244. errorBlock(error);
  245. }];
  246. return operation;
  247. }
  248. - (void)cancelRequestWithURL:(NSString *)url {
  249. if (url == nil) {
  250. return;
  251. }
  252. @synchronized(self) {
  253. [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
  254. if ([task isKindOfClass:[NSURLSessionTask class]]
  255. && [task.currentRequest.URL.absoluteString hasSuffix:url]) {
  256. [task cancel];
  257. [[self allTasks] removeObject:task];
  258. return;
  259. }
  260. }];
  261. };
  262. }
  263. - (void)cancelAllRequest {
  264. @synchronized(self) {
  265. [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
  266. if ([task isKindOfClass:[NSURLSessionTask class]]) {
  267. [task cancel];
  268. }
  269. }];
  270. [[self allTasks] removeAllObjects];
  271. };
  272. }
  273. - (NSMutableArray *)allTasks {
  274. static dispatch_once_t onceToken;
  275. dispatch_once(&onceToken, ^{
  276. if (sg_requestTasks == nil) {
  277. sg_requestTasks = [[NSMutableArray alloc] init];
  278. }
  279. });
  280. return sg_requestTasks;
  281. }
  282. - (NSString *)fileName:(NSString *)url params:(NSDictionary *)params
  283. {
  284. NSMutableString *mStr = [NSMutableString stringWithString:url];
  285. if (params != nil) {
  286. NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
  287. NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  288. [mStr appendString:str];
  289. }
  290. return mStr;
  291. }
  292. - (YBCache *)getCache:(YBCacheType)cacheType url:(NSString *)url params:(NSDictionary *)params withResult:(ZmzBlock)resultBlock
  293. {
  294. //缓存数据的文件名
  295. NSString *fileName = [self fileName:url params:params];
  296. NSData *data = [YBCacheTool getCacheFileName:fileName];
  297. YBCache *cache = [[YBCache alloc] init];
  298. cache.fileName = fileName;
  299. if (data.length) {
  300. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
  301. if (cacheType == YBCacheTypeReloadIgnoringLocalCacheData) {//忽略缓存,重新请求
  302. } else if (cacheType == YBCacheTypeReturnCacheDataDontLoad) {//有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)
  303. if (resultBlock) {
  304. resultBlock(dict,nil,YES);
  305. }
  306. } else if (cacheType == YBCacheTypeReturnCacheDataElseLoad) {//有缓存就用缓存,没有缓存就重新请求(用于数据不变时)
  307. if (resultBlock) {
  308. resultBlock(dict,nil,YES);
  309. }
  310. cache.result = YES;
  311. } else if (cacheType == YBCacheTypeReturnCacheDataThenLoad) {///有缓存就先返回缓存,同步请求数据
  312. if (resultBlock) {
  313. resultBlock(dict,nil,YES);
  314. }
  315. } else if (cacheType == YBCacheTypeReturnCacheDataExpireThenLoad) {//有缓存 判断是否过期了没有 没有就返回缓存
  316. //判断是否过期
  317. if (![YBCacheTool isExpire:fileName]) {
  318. if (resultBlock) {
  319. resultBlock(dict,nil,YES);
  320. }
  321. cache.result = YES;
  322. }
  323. }
  324. }
  325. return cache;
  326. }
  327. @end