省钱达人

ZmzAFNetworking.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. /**
  14. * 存放 网络请求的线程
  15. */
  16. static NSMutableArray *sg_requestTasks;
  17. static NSString *const MAIN_URLL = BaseURL;
  18. @implementation YBCache
  19. @end
  20. static char *NSErrorStatusCodeKey = "NSErrorStatusCodeKey";
  21. @implementation NSError (YBHttp)
  22. - (void)setStatusCode:(NSInteger)statusCode
  23. {
  24. objc_setAssociatedObject(self, NSErrorStatusCodeKey, @(statusCode), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  25. }
  26. - (NSInteger)statusCode
  27. {
  28. return [objc_getAssociatedObject(self, NSErrorStatusCodeKey) integerValue];
  29. }
  30. @end
  31. @interface ZmzAFNetworking()
  32. @property (nonatomic, strong)AFHTTPSessionManager *manager;
  33. @property (nonatomic, assign, getter=isConnected) BOOL connected;/**<网络是否连接*/
  34. @property (nonatomic, retain) NSURLSessionTask *task;
  35. @end
  36. @implementation ZmzAFNetworking
  37. //-(AFHTTPSessionManager *)manager{
  38. // static AFHTTPSessionManager *rmanager = nil;
  39. // static dispatch_once_t onceToken;
  40. // dispatch_once(&onceToken, ^{
  41. // rmanager = [AFHTTPSessionManager manager];
  42. //
  43. // rmanager.responseSerializer = [AFJSONResponseSerializer serializer];
  44. // rmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/jpg",@"application/x-javascript",@"keep-alive", nil];
  45. // // 设置超时时间
  46. // [rmanager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
  47. // rmanager.requestSerializer.timeoutInterval = 60.f;
  48. // [rmanager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
  49. //
  50. // });
  51. // return rmanager;
  52. //}
  53. - (AFHTTPSessionManager *)manager {
  54. // 1.创建请求管理者
  55. AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
  56. mgr.requestSerializer = [AFJSONRequestSerializer serializer]; // 解析为data
  57. mgr.responseSerializer = [AFJSONResponseSerializer serializer];
  58. mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/jpg",@"application/x-javascript",@"keep-alive", nil];
  59. mgr.requestSerializer.timeoutInterval = 15;
  60. NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
  61. NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
  62. [mgr.requestSerializer setValue:app_Version forHTTPHeaderField:@"version"];
  63. [mgr.requestSerializer setValue:Channel_id forHTTPHeaderField:@"source"];
  64. if ([AccountTool isLogin]) {
  65. NSString *token = [AccountTool account].token;
  66. [mgr.requestSerializer setValue:token forHTTPHeaderField:@"token"];
  67. }
  68. // jcytesttoken
  69. NSString *sex = [[NSUserDefaults standardUserDefaults] objectForKey:UserSexKey];
  70. [mgr.requestSerializer setValue:sex forHTTPHeaderField:@"sex"];
  71. return mgr;
  72. }
  73. - (BOOL)isConnected {
  74. struct sockaddr zeroAddress;
  75. bzero(&zeroAddress, sizeof(zeroAddress));
  76. zeroAddress.sa_len = sizeof(zeroAddress);
  77. zeroAddress.sa_family = AF_INET;
  78. SCNetworkReachabilityRef defaultRouteReachability =
  79. SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
  80. SCNetworkReachabilityFlags flags;
  81. BOOL didRetrieveFlags =
  82. SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
  83. CFRelease(defaultRouteReachability);
  84. if (!didRetrieveFlags) {
  85. printf("Error. Count not recover network reachability flags\n");
  86. return NO;
  87. }
  88. BOOL isReachable = flags & kSCNetworkFlagsReachable;
  89. BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
  90. return (isReachable && !needsConnection) ? YES : NO;
  91. }
  92. -(void)requsetWithPath:(NSString *)path withParams:(NSDictionary *)params withCacheType:(YBCacheType)cacheType withRequestType:(NetworkRequestType)type withResult:(ZmzBlock)resultBlock{
  93. if (!self.isConnected) {
  94. NSLog(@"没有网络,建议在手机设置中打开网络");
  95. // return;
  96. }
  97. switch (type) {
  98. case NetworkGetType:
  99. {
  100. YBCache *cache = [self getCache:cacheType url:path params:params withResult:resultBlock];
  101. NSString *fileName = cache.fileName;
  102. if (cache.result) return;
  103. [self.manager GET:path parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
  104. // YBLog(@"---------%lld", downloadProgress.totalUnitCount);
  105. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  106. if (resultBlock) {
  107. //缓存数据
  108. NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
  109. [YBCacheTool cacheForData:data fileName:fileName];
  110. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  111. }
  112. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  113. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  114. }];
  115. }
  116. break;
  117. case NetworkPostType:
  118. {
  119. NSString *cutPath = [NSString stringWithFormat:@"%@",path];
  120. /*
  121. [self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
  122. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  123. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  124. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  125. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  126. }];
  127. */
  128. //缓存数据的文件名 data
  129. YBCache *cache = [self getCache:cacheType url:cutPath params:params withResult:resultBlock];
  130. NSString *fileName = cache.fileName;
  131. if (cache.result) return;
  132. [self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
  133. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  134. if (resultBlock) {
  135. //缓存数据
  136. NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
  137. [YBCacheTool cacheForData:data fileName:fileName];
  138. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  139. }
  140. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  141. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  142. }];
  143. }
  144. break;
  145. default:
  146. break;
  147. }
  148. }
  149. -(void)downloadWithrequest:(NSString *)urlString downloadpath:(NSString *)downloadpath downloadblock:(ZmzDownBlock)downloadblock{
  150. if (!self.connected) {
  151. return;
  152. }
  153. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
  154. self.task = [self.manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
  155. NSURL *desturl = [NSURL fileURLWithPath:downloadpath];
  156. return desturl;
  157. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
  158. downloadblock(response,filePath,error);
  159. }];
  160. [self.task resume];
  161. }
  162. - (void)handleRequestResultWithDataTask:(NSURLSessionDataTask *)task
  163. responseObject:(id)responseObject
  164. error:(NSError *)error
  165. resultBlock:(ZmzBlock)resultBlock {
  166. //do something here...
  167. NSLog(@"%@==-==%@",responseObject,error);
  168. if(resultBlock) {
  169. resultBlock(responseObject,error,NO);
  170. }
  171. }
  172. - (NSURLSessionTask *)uploadImageWithUrl:(NSString *)url
  173. WithParams:(NSDictionary*)params
  174. image:(NSData *)imageData
  175. filename:(NSString *)name
  176. mimeType:(NSString *)mimetype
  177. completion:(requestSuccessBlock)completion
  178. errorBlock:(requestFailureBlock)errorBlock{
  179. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  180. AFHTTPSessionManager *manager = [self manager];
  181. NSURLSessionTask *operation = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  182. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  183. formatter.dateFormat = @"yyyyMMddHHmmss";
  184. NSString *str = [formatter stringFromDate:[NSDate date]];
  185. NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
  186. // 上传图片,以文件流的格式
  187. [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:mimetype];
  188. } progress:^(NSProgress * _Nonnull uploadProgress) {
  189. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  190. completion(responseObject);
  191. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  192. errorBlock(error);
  193. }];
  194. return operation;
  195. }
  196. - (NSURLSessionTask *)uploadVedioWithUrl:(NSString *)url
  197. WithParams:(NSDictionary*)params
  198. image:(NSData *)vedioData
  199. filename:(NSString *)name
  200. mimeType:(NSString *)mimetype
  201. completion:(requestSuccessBlock)completion
  202. errorBlock:(requestFailureBlock)errorBlock{
  203. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  204. AFHTTPSessionManager *manager = [self manager];
  205. NSURLSessionTask *operation = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  206. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  207. formatter.dateFormat = @"yyyyMMddHHmmss";
  208. NSString *str = [formatter stringFromDate:[NSDate date]];
  209. NSString *fileName = [NSString stringWithFormat:@"%@.mp4",str];
  210. [formData appendPartWithFileData:vedioData name:name fileName:fileName mimeType:mimetype];
  211. } progress:^(NSProgress * _Nonnull uploadProgress) {
  212. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  213. completion(responseObject);
  214. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  215. errorBlock(error);
  216. }];
  217. return operation;
  218. }
  219. - (void)cancelRequestWithURL:(NSString *)url {
  220. if (url == nil) {
  221. return;
  222. }
  223. @synchronized(self) {
  224. [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
  225. if ([task isKindOfClass:[NSURLSessionTask class]]
  226. && [task.currentRequest.URL.absoluteString hasSuffix:url]) {
  227. [task cancel];
  228. [[self allTasks] removeObject:task];
  229. return;
  230. }
  231. }];
  232. };
  233. }
  234. - (void)cancelAllRequest {
  235. @synchronized(self) {
  236. [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
  237. if ([task isKindOfClass:[NSURLSessionTask class]]) {
  238. [task cancel];
  239. }
  240. }];
  241. [[self allTasks] removeAllObjects];
  242. };
  243. }
  244. - (NSMutableArray *)allTasks {
  245. static dispatch_once_t onceToken;
  246. dispatch_once(&onceToken, ^{
  247. if (sg_requestTasks == nil) {
  248. sg_requestTasks = [[NSMutableArray alloc] init];
  249. }
  250. });
  251. return sg_requestTasks;
  252. }
  253. - (NSString *)fileName:(NSString *)url params:(NSDictionary *)params
  254. {
  255. NSMutableString *mStr = [NSMutableString stringWithString:url];
  256. if (params != nil) {
  257. NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
  258. NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  259. [mStr appendString:str];
  260. }
  261. return mStr;
  262. }
  263. - (YBCache *)getCache:(YBCacheType)cacheType url:(NSString *)url params:(NSDictionary *)params withResult:(ZmzBlock)resultBlock
  264. {
  265. //缓存数据的文件名
  266. NSString *fileName = [self fileName:url params:params];
  267. NSData *data = [YBCacheTool getCacheFileName:fileName];
  268. YBCache *cache = [[YBCache alloc] init];
  269. cache.fileName = fileName;
  270. if (data.length) {
  271. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
  272. if (cacheType == YBCacheTypeReloadIgnoringLocalCacheData) {//忽略缓存,重新请求
  273. } else if (cacheType == YBCacheTypeReturnCacheDataDontLoad) {//有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)
  274. if (resultBlock) {
  275. resultBlock(dict,nil,YES);
  276. }
  277. } else if (cacheType == YBCacheTypeReturnCacheDataElseLoad) {//有缓存就用缓存,没有缓存就重新请求(用于数据不变时)
  278. if (resultBlock) {
  279. resultBlock(dict,nil,YES);
  280. }
  281. cache.result = YES;
  282. } else if (cacheType == YBCacheTypeReturnCacheDataThenLoad) {///有缓存就先返回缓存,同步请求数据
  283. if (resultBlock) {
  284. resultBlock(dict,nil,YES);
  285. }
  286. } else if (cacheType == YBCacheTypeReturnCacheDataExpireThenLoad) {//有缓存 判断是否过期了没有 没有就返回缓存
  287. //判断是否过期
  288. if (![YBCacheTool isExpire:fileName]) {
  289. if (resultBlock) {
  290. resultBlock(dict,nil,YES);
  291. }
  292. cache.result = YES;
  293. }
  294. }
  295. }
  296. return cache;
  297. }
  298. @end