天天省钱快报

ZmzAFNetworking.m 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. if ([responseObject[@"errno"] isEqualToString:@"0"]) {
  108. //缓存数据
  109. NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
  110. [YBCacheTool cacheForData:data fileName:fileName];
  111. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  112. }else {
  113. //errno不是0则返回错误
  114. NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
  115. NSString *desc = NSLocalizedString(@"Unable to…", @"");
  116. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
  117. NSInteger code = [responseObject[@"errno"] integerValue];
  118. NSError *error = [NSError errorWithDomain:domain
  119. code:code
  120. userInfo:userInfo];
  121. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  122. }
  123. }
  124. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  125. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  126. }];
  127. }
  128. break;
  129. case NetworkPostType:
  130. {
  131. NSString *cutPath = [NSString stringWithFormat:@"%@",path];
  132. /*
  133. [self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
  134. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  135. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  136. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  137. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  138. }];
  139. */
  140. //缓存数据的文件名 data
  141. YBCache *cache = [self getCache:cacheType url:cutPath params:params withResult:resultBlock];
  142. NSString *fileName = cache.fileName;
  143. if (cache.result) return;
  144. [self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
  145. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  146. if (resultBlock) {
  147. if ([responseObject[@"errno"] isEqualToString:@"0"]) {
  148. //缓存数据
  149. NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
  150. [YBCacheTool cacheForData:data fileName:fileName];
  151. [self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];
  152. }else {
  153. //errno不是0则返回错误
  154. NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
  155. NSString *desc = NSLocalizedString(@"Unable to…", @"");
  156. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
  157. NSInteger code = [responseObject[@"errno"] integerValue];
  158. NSError *error = [NSError errorWithDomain:domain
  159. code:code
  160. userInfo:userInfo];
  161. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  162. }
  163. }
  164. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  165. [self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];
  166. }];
  167. }
  168. break;
  169. default:
  170. break;
  171. }
  172. }
  173. -(void)downloadWithrequest:(NSString *)urlString downloadpath:(NSString *)downloadpath downloadblock:(ZmzDownBlock)downloadblock{
  174. if (!self.connected) {
  175. return;
  176. }
  177. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
  178. self.task = [self.manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
  179. NSURL *desturl = [NSURL fileURLWithPath:downloadpath];
  180. return desturl;
  181. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
  182. downloadblock(response,filePath,error);
  183. }];
  184. [self.task resume];
  185. }
  186. - (void)handleRequestResultWithDataTask:(NSURLSessionDataTask *)task
  187. responseObject:(id)responseObject
  188. error:(NSError *)error
  189. resultBlock:(ZmzBlock)resultBlock {
  190. //do something here...
  191. // NSLog(@"%@==-==%@",responseObject,error);
  192. if(resultBlock) {
  193. resultBlock(responseObject,error,NO);
  194. }
  195. }
  196. - (NSURLSessionTask *)uploadImageWithUrl:(NSString *)url
  197. WithParams:(NSDictionary*)params
  198. image:(NSData *)imageData
  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:@"%@.jpg",str];
  210. // 上传图片,以文件流的格式
  211. [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:mimetype];
  212. } progress:^(NSProgress * _Nonnull uploadProgress) {
  213. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  214. completion(responseObject);
  215. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  216. errorBlock(error);
  217. }];
  218. return operation;
  219. }
  220. - (NSURLSessionTask *)uploadVedioWithUrl:(NSString *)url
  221. WithParams:(NSDictionary*)params
  222. image:(NSData *)vedioData
  223. filename:(NSString *)name
  224. mimeType:(NSString *)mimetype
  225. completion:(requestSuccessBlock)completion
  226. errorBlock:(requestFailureBlock)errorBlock{
  227. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  228. AFHTTPSessionManager *manager = [self manager];
  229. NSURLSessionTask *operation = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  230. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  231. formatter.dateFormat = @"yyyyMMddHHmmss";
  232. NSString *str = [formatter stringFromDate:[NSDate date]];
  233. NSString *fileName = [NSString stringWithFormat:@"%@.mp4",str];
  234. [formData appendPartWithFileData:vedioData name:name fileName:fileName mimeType:mimetype];
  235. } progress:^(NSProgress * _Nonnull uploadProgress) {
  236. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  237. completion(responseObject);
  238. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  239. errorBlock(error);
  240. }];
  241. return operation;
  242. }
  243. - (void)cancelRequestWithURL:(NSString *)url {
  244. if (url == nil) {
  245. return;
  246. }
  247. @synchronized(self) {
  248. [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
  249. if ([task isKindOfClass:[NSURLSessionTask class]]
  250. && [task.currentRequest.URL.absoluteString hasSuffix:url]) {
  251. [task cancel];
  252. [[self allTasks] removeObject:task];
  253. return;
  254. }
  255. }];
  256. };
  257. }
  258. - (void)cancelAllRequest {
  259. @synchronized(self) {
  260. [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
  261. if ([task isKindOfClass:[NSURLSessionTask class]]) {
  262. [task cancel];
  263. }
  264. }];
  265. [[self allTasks] removeAllObjects];
  266. };
  267. }
  268. - (NSMutableArray *)allTasks {
  269. static dispatch_once_t onceToken;
  270. dispatch_once(&onceToken, ^{
  271. if (sg_requestTasks == nil) {
  272. sg_requestTasks = [[NSMutableArray alloc] init];
  273. }
  274. });
  275. return sg_requestTasks;
  276. }
  277. - (NSString *)fileName:(NSString *)url params:(NSDictionary *)params
  278. {
  279. NSMutableString *mStr = [NSMutableString stringWithString:url];
  280. if (params != nil) {
  281. NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
  282. NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  283. [mStr appendString:str];
  284. }
  285. return mStr;
  286. }
  287. - (YBCache *)getCache:(YBCacheType)cacheType url:(NSString *)url params:(NSDictionary *)params withResult:(ZmzBlock)resultBlock
  288. {
  289. //缓存数据的文件名
  290. NSString *fileName = [self fileName:url params:params];
  291. NSData *data = [YBCacheTool getCacheFileName:fileName];
  292. YBCache *cache = [[YBCache alloc] init];
  293. cache.fileName = fileName;
  294. if (data.length) {
  295. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
  296. if (cacheType == YBCacheTypeReloadIgnoringLocalCacheData) {//忽略缓存,重新请求
  297. } else if (cacheType == YBCacheTypeReturnCacheDataDontLoad) {//有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)
  298. if (resultBlock) {
  299. resultBlock(dict,nil,YES);
  300. }
  301. } else if (cacheType == YBCacheTypeReturnCacheDataElseLoad) {//有缓存就用缓存,没有缓存就重新请求(用于数据不变时)
  302. if (resultBlock) {
  303. resultBlock(dict,nil,YES);
  304. }
  305. cache.result = YES;
  306. } else if (cacheType == YBCacheTypeReturnCacheDataThenLoad) {///有缓存就先返回缓存,同步请求数据
  307. if (resultBlock) {
  308. resultBlock(dict,nil,YES);
  309. }
  310. } else if (cacheType == YBCacheTypeReturnCacheDataExpireThenLoad) {//有缓存 判断是否过期了没有 没有就返回缓存
  311. //判断是否过期
  312. if (![YBCacheTool isExpire:fileName]) {
  313. if (resultBlock) {
  314. resultBlock(dict,nil,YES);
  315. }
  316. cache.result = YES;
  317. }
  318. }
  319. }
  320. return cache;
  321. }
  322. @end