Brak opisu

FLDataCenter.m 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //
  2. // DataCenter.m
  3. // FirstLink
  4. //
  5. // Created by unicode on 14-9-15.
  6. // Copyright (c) 2014年 FirstLink. All rights reserved.
  7. //
  8. #import "FLDataCenter.h"
  9. #import "FLControllerHelper.h"
  10. #import "FKReachabilityUtil.h"
  11. #import "FKLogTransformEntity.h"
  12. #import "FKJsonMock.h"
  13. @interface FLDataCenter ()
  14. @property (nonatomic, strong) FLLocalStorage *localStorage;
  15. @property (nonatomic, strong) AFHTTPSessionManager *manager;
  16. @end
  17. @implementation FLDataCenter
  18. +(FLDataCenter*)sharedDataCenter {
  19. static dispatch_once_t once;
  20. static FLDataCenter *sharedDataCenter;
  21. dispatch_once(&once, ^ {
  22. sharedDataCenter = [[self alloc] init];
  23. });
  24. return sharedDataCenter;
  25. }
  26. - (instancetype)init {
  27. self = [super init];
  28. if (self) {
  29. _localStorage = [FLLocalStorage new];
  30. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  31. configuration.timeoutIntervalForRequest = 15;
  32. _manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
  33. _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  34. _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  35. }
  36. return self;
  37. }
  38. #pragma mark - Method
  39. - (MSGHeader*)parserMSGHeader:(NSDictionary*)jsonDict {
  40. MSGHeader *header = [[MSGHeader alloc] init];
  41. [header mts_setValuesForKeysWithDictionary:jsonDict];
  42. return header;
  43. }
  44. - (NSString*)parserErrorMessage:(NSDictionary*)jsonDict {
  45. if ([jsonDict isKindOfClass:[NSDictionary class]]) {
  46. if ([jsonDict objectForKey:@"message"] != [NSNull null]) {
  47. NSString *msg = [jsonDict objectForKey:@"message"];
  48. return msg;
  49. }
  50. }
  51. return @"数据加载失败";
  52. }
  53. #pragma mark - Block API
  54. - (void)POST:(NSString *)URLString
  55. parameters:(NSDictionary *)parameters
  56. success:(void (^)(MSGHeader *, id))success
  57. failure:(void (^)(MSGHeader *, NSError *))failure
  58. {
  59. __weak typeof(self) weakSelf = self;
  60. [self.manager POST:URLString
  61. parameters:parameters
  62. progress:^(NSProgress * _Nonnull uploadProgress) {
  63. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  64. NSError *jsonError;
  65. NSDictionary *responseString = [NSJSONSerialization JSONObjectWithData: responseObject
  66. options: NSJSONReadingMutableContainers
  67. error: &jsonError];
  68. if (!jsonError && [responseString isKindOfClass:[NSDictionary class]]) {
  69. MSGHeader *msgHead = [weakSelf parserMSGHeader:responseString];
  70. if ([msgHead.code intValue] == RESPONSE_MSG_NORMAL) {
  71. success(msgHead, responseString);
  72. } else if ([msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION) {
  73. [[FKUserManager sharedManager] localLogout];
  74. [FLControllerHelper presentLoginViewController];
  75. return ;
  76. } else if ([msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION) {
  77. success(msgHead, [weakSelf parserErrorMessage:responseString]);
  78. } else {
  79. success(msgHead, @"数据加载失败");
  80. }
  81. } else {
  82. success([[MSGHeader alloc] init], responseObject);
  83. }
  84. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  85. failure(nil, error);
  86. // if ([error.domain isEqualToString:@"NSURLErrorDomain"]
  87. // || [error.domain isEqualToString:@"NSCocoaErrorDomain"]) {
  88. // [[FKServerUtil sharedInstance] receiveErrorDomain];
  89. // }
  90. }];
  91. }
  92. -(void)POSTData:(NSData*)data
  93. name:(NSString*)name
  94. fileName:(NSString*)fileName
  95. mimeType:(NSString*)miniType
  96. url:(NSURL*)url
  97. parameters:(NSDictionary *)parameters
  98. success:(void (^)(MSGHeader *, id))success
  99. progress:(void (^)(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))progress
  100. failure:(void (^)(MSGHeader *, NSError *))failure
  101. {
  102. __weak typeof(self) weakSelf = self;
  103. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
  104. URLString:url.absoluteString
  105. parameters:parameters
  106. constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
  107. {
  108. [formData appendPartWithFileData:data name:name fileName:fileName mimeType:miniType];
  109. } error:nil];
  110. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  111. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  112. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request
  113. progress:^(NSProgress * _Nonnull uploadProgress) {
  114. }
  115. completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  116. if (!error) {
  117. NSError *jsonError;
  118. NSDictionary *responseString = [NSJSONSerialization JSONObjectWithData: responseObject
  119. options: NSJSONReadingMutableContainers
  120. error: &jsonError];
  121. if (!jsonError && [responseString isKindOfClass:[NSDictionary class]]) {
  122. MSGHeader *msgHead = [weakSelf parserMSGHeader:responseString];
  123. if ([msgHead.code intValue] == RESPONSE_MSG_NORMAL) {
  124. success(msgHead, responseString);
  125. } else if ([msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION) {
  126. [[FKUserManager sharedManager] localLogout];
  127. [FLControllerHelper presentLoginViewController];
  128. return ;
  129. } else if ([msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION) {
  130. success(msgHead, [weakSelf parserErrorMessage:responseString]);
  131. } else {
  132. success(msgHead, @"数据加载失败");
  133. }
  134. } else {
  135. success([[MSGHeader alloc] init], @"数据加载失败");
  136. }
  137. } else {
  138. failure(nil, error);
  139. }
  140. }];
  141. [uploadTask resume];
  142. }
  143. #pragma mark - Delegate API
  144. -(void)POST:(NSString *)url
  145. para:(NSDictionary *)para
  146. identify:(int)identify
  147. delegate:(id<FLNetworkDelegate>)delegate {
  148. [self POST:url
  149. para:para
  150. identify:identify
  151. delegate:delegate
  152. userInfo:nil];
  153. }
  154. -(void)POST:(NSString *)url
  155. para:(NSDictionary *)para
  156. identify:(int)identify
  157. delegate:(id<FLNetworkDelegate>)delegate
  158. userInfo:(NSDictionary *)userInfo
  159. {
  160. // CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
  161. #ifdef DEBUG
  162. url = [[FKJsonMock sharedInstance] jsonMockRouterURL:url];
  163. #endif
  164. url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  165. __weak typeof(self) weakSelf = self;
  166. [self.manager POST:url
  167. parameters:para
  168. progress:^(NSProgress * _Nonnull uploadProgress) {
  169. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  170. NSError *jsonError;
  171. NSDictionary *responseString = [NSJSONSerialization JSONObjectWithData: responseObject
  172. options: NSJSONReadingMutableContainers
  173. error: &jsonError];
  174. MSGHeader *msgHead = [[MSGHeader alloc] init];
  175. msgHead = [weakSelf parserMSGHeader:responseString];
  176. // 日志记录
  177. NSString *desc;
  178. if (jsonError || ![responseString isKindOfClass:[NSDictionary class]]
  179. || [msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION
  180. || [msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION ) {
  181. desc = [weakSelf parserErrorMessage:responseString];
  182. }
  183. // CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();
  184. // FKLogTransformEntity *entity = [[FKLogTransformEntity alloc] initWithRTT:(int)((endTime - startTime)*1000)
  185. // size:operation.response.allHeaderFields[@"Content-Length"]
  186. // method:nil
  187. // url:operation.request.URL.absoluteString
  188. // para:para
  189. // status:operation.response.statusCode
  190. // desc:desc];
  191. // [FKLogUtil logTransformEntity:entity];
  192. // 返回请求
  193. if (!jsonError && [responseString isKindOfClass:[NSDictionary class]]) {
  194. if ([msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION) {
  195. [[FKUserManager sharedManager] localLogout];
  196. [FLControllerHelper presentLoginViewController];
  197. } else {
  198. if ([msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION) {
  199. msgHead.msg = desc;
  200. }
  201. if ([delegate respondsToSelector:@selector(networkDidSuccessResponse:identify:header:)]) {
  202. [delegate networkDidSuccessResponse:responseString identify:identify header:msgHead];
  203. } else if ([delegate respondsToSelector:@selector(networkDidSuccessResponse:identify:header:userInfo:)]) {
  204. [delegate networkDidSuccessResponse:responseString identify:identify header:msgHead userInfo:userInfo];
  205. }
  206. }
  207. } else {
  208. msgHead.msg = desc;
  209. if ([delegate respondsToSelector:@selector(networkDidReceiveError:identify:header:)]) {
  210. [delegate networkDidReceiveError:jsonError identify:identify header:msgHead];
  211. }
  212. }
  213. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  214. MSGHeader *msgHead = [[MSGHeader alloc] init];
  215. msgHead.msg = error.localizedDescription;
  216. // 日志记录
  217. // CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();
  218. // FKLogTransformEntity *entity = [[FKLogTransformEntity alloc] initWithRTT:(int)((endTime - startTime)*1000)
  219. // size:operation.response.allHeaderFields[@"Content-Length"]
  220. // method:nil
  221. // url:operation.request.URL.absoluteString
  222. // para:para
  223. // status:operation.response.statusCode
  224. // desc:msgHead.msg];
  225. // [FKLogUtil logTransformEntity:entity];
  226. //
  227. // if ([error.domain isEqualToString:@"NSURLErrorDomain"]
  228. // || [error.domain isEqualToString:@"NSCocoaErrorDomain"]) {
  229. // [[FKServerUtil sharedInstance] receiveErrorDomain];
  230. // }
  231. if (![[FKReachabilityUtil sharedInstance] isReachable]) {
  232. if ([delegate respondsToSelector:@selector(networkNotReachable)]) {
  233. [delegate networkNotReachable];
  234. return;
  235. }
  236. }
  237. if ([delegate respondsToSelector:@selector(networkDidReceiveError:identify:header:)]) {
  238. [delegate networkDidReceiveError:error identify:identify header:msgHead];
  239. return;
  240. }
  241. }];
  242. }
  243. #pragma mark - Local DataBase API
  244. + (FMDatabase *)defaultDatabase {
  245. return [[FLDataCenter sharedDataCenter].localStorage getDatabase];
  246. }
  247. @end