123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284 |
- //
- // 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<AFMultipartFormData> 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<FLNetworkDelegate>)delegate {
- [self POST:url
- para:para
- identify:identify
- delegate:delegate
- userInfo:nil];
- }
- -(void)POST:(NSString *)url
- para:(NSDictionary *)para
- identify:(int)identify
- delegate:(id<FLNetworkDelegate>)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
|