// // DataCenter.m // FirstLink // // Created by unicode on 14-9-15. // Copyright (c) 2014年 FirstLink. All rights reserved. // #import "FLDataCenter.h" #import "FLControllerHelper.h" #import "FKReachabilityUtil.h" #import "FKLogTransformEntity.h" #import "FKJsonMock.h" @interface FLDataCenter () @property (nonatomic, strong) FLLocalStorage *localStorage; @property (nonatomic, strong) AFHTTPSessionManager *manager; @end @implementation FLDataCenter +(FLDataCenter*)sharedDataCenter { static dispatch_once_t once; static FLDataCenter *sharedDataCenter; dispatch_once(&once, ^ { sharedDataCenter = [[self alloc] init]; }); return sharedDataCenter; } - (instancetype)init { self = [super init]; if (self) { _localStorage = [FLLocalStorage new]; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; configuration.timeoutIntervalForRequest = 15; _manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration]; _manager.requestSerializer = [AFHTTPRequestSerializer serializer]; _manager.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; } #pragma mark - Method - (MSGHeader*)parserMSGHeader:(NSDictionary*)jsonDict { MSGHeader *header = [[MSGHeader alloc] init]; [header mts_setValuesForKeysWithDictionary:jsonDict]; return header; } - (NSString*)parserErrorMessage:(NSDictionary*)jsonDict { if ([jsonDict isKindOfClass:[NSDictionary class]]) { if ([jsonDict objectForKey:@"message"] != [NSNull null]) { NSString *msg = [jsonDict objectForKey:@"message"]; return msg; } } return @"数据加载失败"; } #pragma mark - Block API - (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(MSGHeader *, id))success failure:(void (^)(MSGHeader *, NSError *))failure { __weak typeof(self) weakSelf = self; [self.manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSError *jsonError; NSDictionary *responseString = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableContainers error: &jsonError]; if (!jsonError && [responseString isKindOfClass:[NSDictionary class]]) { MSGHeader *msgHead = [weakSelf parserMSGHeader:responseString]; if ([msgHead.code intValue] == RESPONSE_MSG_NORMAL) { success(msgHead, responseString); } else if ([msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION) { [[FKUserManager sharedManager] localLogout]; [FLControllerHelper presentLoginViewController]; return ; } else if ([msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION) { success(msgHead, [weakSelf parserErrorMessage:responseString]); } else { success(msgHead, @"数据加载失败"); } } else { success([[MSGHeader alloc] init], responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(nil, error); // if ([error.domain isEqualToString:@"NSURLErrorDomain"] // || [error.domain isEqualToString:@"NSCocoaErrorDomain"]) { // [[FKServerUtil sharedInstance] receiveErrorDomain]; // } }]; } -(void)POSTData:(NSData*)data name:(NSString*)name fileName:(NSString*)fileName mimeType:(NSString*)miniType url:(NSURL*)url parameters:(NSDictionary *)parameters success:(void (^)(MSGHeader *, id))success progress:(void (^)(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))progress failure:(void (^)(MSGHeader *, NSError *))failure { __weak typeof(self) weakSelf = self; NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url.absoluteString parameters:parameters constructingBodyWithBlock:^(id formData) { [formData appendPartWithFileData:data name:name fileName:fileName mimeType:miniType]; } error:nil]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) { } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { NSError *jsonError; NSDictionary *responseString = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableContainers error: &jsonError]; if (!jsonError && [responseString isKindOfClass:[NSDictionary class]]) { MSGHeader *msgHead = [weakSelf parserMSGHeader:responseString]; if ([msgHead.code intValue] == RESPONSE_MSG_NORMAL) { success(msgHead, responseString); } else if ([msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION) { [[FKUserManager sharedManager] localLogout]; [FLControllerHelper presentLoginViewController]; return ; } else if ([msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION) { success(msgHead, [weakSelf parserErrorMessage:responseString]); } else { success(msgHead, @"数据加载失败"); } } else { success([[MSGHeader alloc] init], @"数据加载失败"); } } else { failure(nil, error); } }]; [uploadTask resume]; } #pragma mark - Delegate API -(void)POST:(NSString *)url para:(NSDictionary *)para identify:(int)identify delegate:(id)delegate { [self POST:url para:para identify:identify delegate:delegate userInfo:nil]; } -(void)POST:(NSString *)url para:(NSDictionary *)para identify:(int)identify delegate:(id)delegate userInfo:(NSDictionary *)userInfo { // CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent(); #ifdef DEBUG url = [[FKJsonMock sharedInstance] jsonMockRouterURL:url]; #endif url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; __weak typeof(self) weakSelf = self; [self.manager POST:url parameters:para progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSError *jsonError; NSDictionary *responseString = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableContainers error: &jsonError]; MSGHeader *msgHead = [[MSGHeader alloc] init]; msgHead = [weakSelf parserMSGHeader:responseString]; // 日志记录 NSString *desc; if (jsonError || ![responseString isKindOfClass:[NSDictionary class]] || [msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION || [msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION ) { desc = [weakSelf parserErrorMessage:responseString]; } // CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent(); // FKLogTransformEntity *entity = [[FKLogTransformEntity alloc] initWithRTT:(int)((endTime - startTime)*1000) // size:operation.response.allHeaderFields[@"Content-Length"] // method:nil // url:operation.request.URL.absoluteString // para:para // status:operation.response.statusCode // desc:desc]; // [FKLogUtil logTransformEntity:entity]; // 返回请求 if (!jsonError && [responseString isKindOfClass:[NSDictionary class]]) { if ([msgHead.code intValue] == RESPONSE_MSG_ACCESS_EXCEPTION) { [[FKUserManager sharedManager] localLogout]; [FLControllerHelper presentLoginViewController]; } else { if ([msgHead.code intValue] == RESPONSE_MSG_BUSINESS_EXCEPTION) { msgHead.msg = desc; } if ([delegate respondsToSelector:@selector(networkDidSuccessResponse:identify:header:)]) { [delegate networkDidSuccessResponse:responseString identify:identify header:msgHead]; } else if ([delegate respondsToSelector:@selector(networkDidSuccessResponse:identify:header:userInfo:)]) { [delegate networkDidSuccessResponse:responseString identify:identify header:msgHead userInfo:userInfo]; } } } else { msgHead.msg = desc; if ([delegate respondsToSelector:@selector(networkDidReceiveError:identify:header:)]) { [delegate networkDidReceiveError:jsonError identify:identify header:msgHead]; } } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { MSGHeader *msgHead = [[MSGHeader alloc] init]; msgHead.msg = error.localizedDescription; // 日志记录 // CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent(); // FKLogTransformEntity *entity = [[FKLogTransformEntity alloc] initWithRTT:(int)((endTime - startTime)*1000) // size:operation.response.allHeaderFields[@"Content-Length"] // method:nil // url:operation.request.URL.absoluteString // para:para // status:operation.response.statusCode // desc:msgHead.msg]; // [FKLogUtil logTransformEntity:entity]; // // if ([error.domain isEqualToString:@"NSURLErrorDomain"] // || [error.domain isEqualToString:@"NSCocoaErrorDomain"]) { // [[FKServerUtil sharedInstance] receiveErrorDomain]; // } if (![[FKReachabilityUtil sharedInstance] isReachable]) { if ([delegate respondsToSelector:@selector(networkNotReachable)]) { [delegate networkNotReachable]; return; } } if ([delegate respondsToSelector:@selector(networkDidReceiveError:identify:header:)]) { [delegate networkDidReceiveError:error identify:identify header:msgHead]; return; } }]; } #pragma mark - Local DataBase API + (FMDatabase *)defaultDatabase { return [[FLDataCenter sharedDataCenter].localStorage getDatabase]; } @end