RequestHandler.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //
  2. // RequestHandler.m
  3. // Giwa
  4. //
  5. // Created by Jason Lee on 12/16/14.
  6. // Copyright (c) jasondevelop. All rights reserved.
  7. //
  8. #import "JDObject.h"
  9. #import "AFHTTPRequestOperation.h"
  10. #import "JDJSONModel.h"
  11. #import "RequestHandler.h"
  12. #import "AFHTTPRequestOperationManager.h"
  13. #import "AFHTTPRequestOperationManager+Synchronous.h"
  14. #define NSEUCKREncoding -2147481280
  15. @interface RequestHandler () {
  16. NSString *_requestPath;
  17. }
  18. @end
  19. @implementation RequestHandler
  20. #pragma mark - URL Encoding
  21. - (NSString *)URLEncodedString:(NSString *)string
  22. {
  23. return [string stringByAddingPercentEscapesUsingEncoding:NSEUCKREncoding];
  24. // NSString *encodedString = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
  25. // (CFStringRef)string,
  26. // NULL,
  27. // (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  28. // kCFStringEncodingUTF8);
  29. // return encodedString;
  30. }
  31. //- (NSString*)URLDecodedString:(NSString *)string
  32. //{
  33. //
  34. //
  35. //
  36. // NSString *result = (__bridge NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
  37. // (CFStringRef)string,
  38. // CFSTR(""),
  39. // kCFStringEncodingUTF8);
  40. // return result;
  41. //}
  42. #pragma mark - Prepare Request
  43. - (void)sendRequest {
  44. [[JDFacade facade] loadIndicator:YES allowUserInteraction:NO];
  45. }
  46. - (void)finishRequest {
  47. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  48. }
  49. #pragma mark - URL Request
  50. - (void)sendAsyncRequestURLString:(NSString *)URLString method:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  51. [self sendRequest];
  52. NSString *encodURLString = [self URLEncodedString:[NSString stringWithFormat:@"%@%@", URLString, path]];
  53. NSLog(@"URL=%@", encodURLString);
  54. NSLog(@"PARAM=%@", parameters);
  55. NSError *error = nil;
  56. BOOL hasFile = NO, isDataImage = NO, isMultipartForm = parameters[ksHTTPMultipartForm] && [parameters[ksHTTPRequestPOST] boolValue] ? YES : NO;
  57. NSData *dataToUpload = nil;
  58. NSString *dataParameter = nil;
  59. NSInteger i = 0;
  60. for (NSObject *obj in parameters.allValues) {//파일형식이 있는지 체크,
  61. if (!hasFile && ([obj isKindOfClass:[UIImage class]] || [obj isKindOfClass:[NSData class]])) {
  62. isDataImage = [obj isKindOfClass:[UIImage class]];
  63. dataToUpload = isDataImage ? UIImageJPEGRepresentation((UIImage *)obj, 1.0) : (NSData *)obj;
  64. dataParameter = parameters.allKeys[i];
  65. hasFile = YES;
  66. break;
  67. }
  68. i++;
  69. }
  70. NSMutableURLRequest *request = nil;
  71. if (!hasFile && !isMultipartForm) {//no image
  72. request = [[AFHTTPRequestSerializer serializer] requestWithMethod:method URLString:encodURLString parameters:parameters error:&error];
  73. } else {//Multipart-form
  74. NSMutableDictionary *tmpParams = [NSMutableDictionary dictionaryWithDictionary:parameters];
  75. [tmpParams removeObjectForKey:dataParameter];
  76. request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:method URLString:encodURLString parameters:tmpParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  77. NSString *fileName = isDataImage ? @"tmp.jpg" : @"tmp.txt";
  78. NSString *mimeType = isDataImage ? @"image/jpeg" : @"application/json"; //text/plain
  79. [formData appendPartWithFileData:dataToUpload name:dataParameter fileName:fileName mimeType:mimeType];
  80. } error:&error];
  81. }
  82. AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  83. op.responseSerializer = [AFJSONResponseSerializer serializer];
  84. [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  85. [self finishRequest];
  86. NSLog(@"\n\nJSON=%@\n\n", responseObject);
  87. if (completion) {
  88. completion(responseObject);
  89. }
  90. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  91. [self finishRequest];
  92. if (failure) {
  93. failure(error);
  94. }
  95. }];
  96. [[NSOperationQueue mainQueue] addOperation:op];
  97. }
  98. - (void)sendAsyncPostRequestURL:(NSString *)URLString path:(NSString *)path parameters:(NSDictionary *)parameters completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  99. [self sendAsyncRequestURLString:URLString method:ksHTTPRequestPOST path:(NSString *)path parameters:parameters completion:completion failure:failure];
  100. }
  101. - (void)sendAsyncGetRequestURL:(NSString *)URLString path:(NSString *)path parameters:(NSDictionary *)parameters completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  102. [self sendAsyncRequestURLString:URLString method:ksHTTPRequestGET path:(NSString *)path parameters:parameters completion:completion failure:failure];
  103. }
  104. #pragma mark - 비동기 API 요청
  105. - (void)sendAsyncGetRequestAPIPath:(NSString *)apiPath parameters:(NSDictionary *)parameters modelClass:(Class)modelClass completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  106. [self sendAsyncRequestAPIPath:apiPath method:ksHTTPRequestGET parameters:parameters modelClass:modelClass showLoadingView:YES completion:completion failure:failure];
  107. }
  108. - (void)sendAsyncPostRequestAPIPath:(NSString *)apiPath parameters:(NSDictionary *)parameters modelClass:(Class)modelClass completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  109. [self sendAsyncRequestAPIPath:apiPath method:ksHTTPRequestPOST parameters:parameters modelClass:modelClass showLoadingView:YES completion:completion failure:failure];
  110. }
  111. - (void)sendAsyncPostRequestAPIPath:(NSString *)apiPath parameters:(NSDictionary *)parameters modelClass:(Class)modelClass showLoadingView:(BOOL)showLoadingView completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  112. [self sendAsyncRequestAPIPath:apiPath method:ksHTTPRequestPOST parameters:parameters modelClass:modelClass showLoadingView:showLoadingView completion:completion failure:failure];
  113. }
  114. - (void)sendAsyncRequestAPIPath:(NSString *)apiPath method:(NSString *)method parameters:(NSDictionary *)parameters modelClass:(Class)modelClass showLoadingView:(BOOL)showLoadingView completion:(RequestHandlerCompletionBlock)completion failure:(RequestHandlerFailureBlock)failure {
  115. _requestPath = apiPath;
  116. if (showLoadingView) {
  117. [self sendRequest];
  118. }
  119. NSString *rootPath = API_ROOT_PATH;
  120. NSString *pathURL = [self URLEncodedString:[NSString stringWithFormat:@"%@%@%@", kAPIServer, rootPath, apiPath]];
  121. NSLog(@"PATH=%@", pathURL);
  122. NSLog(@"PARAM=%@", parameters);
  123. NSError *error = nil;
  124. BOOL hasFile = NO, isDataImage = NO, isMultipartForm = parameters[ksHTTPMultipartForm] && [parameters[ksHTTPRequestPOST] boolValue] ? YES : NO;
  125. NSMutableArray *fileArray = nil;
  126. NSMutableArray *fileParams = nil;
  127. NSInteger index = 0;
  128. for (NSObject *obj in parameters.allValues) {//파일형식이 있는지 체크,
  129. if (([obj isKindOfClass:[UIImage class]] || [obj isKindOfClass:[NSData class]])) {
  130. if (!fileArray) {
  131. fileArray = [[NSMutableArray alloc] init];
  132. fileParams = [[NSMutableArray alloc] init];
  133. hasFile = YES;
  134. }
  135. isDataImage = [obj isKindOfClass:[UIImage class]];
  136. [fileArray addObject:isDataImage ? UIImageJPEGRepresentation((UIImage *)obj, 1.0) : (NSData *)obj];
  137. [fileParams addObject:parameters.allKeys[index]];
  138. }
  139. index++;
  140. }
  141. NSMutableURLRequest *request = nil;
  142. if (!hasFile && !isMultipartForm) {//no file
  143. request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:pathURL parameters:parameters error:&error];
  144. [request setHTTPMethod:method];
  145. [request setTimeoutInterval:kDefaultTimeOut];
  146. [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  147. NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
  148. //FIXME : when production
  149. #ifdef DEBUG_MODE
  150. language = @"ko";
  151. #endif
  152. [request setValue:language forHTTPHeaderField:@"Accept-Language"];
  153. } else {//Multipart-form
  154. NSMutableDictionary *tmpParams = [NSMutableDictionary dictionaryWithDictionary:parameters];
  155. [tmpParams removeObjectForKey:fileParams];
  156. request = [[AFJSONRequestSerializer serializer] multipartFormRequestWithMethod:method URLString:pathURL parameters:tmpParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  157. NSString *mimeType = isDataImage ? @"image/jpeg" : @"text/plain";
  158. NSInteger i = 0;
  159. NSString *name = [fileParams[i] substringToIndex:[fileParams[i] rangeOfString:@"_"].location];
  160. for (NSData *dataToUpload in fileArray) {
  161. NSString *fileName = isDataImage ? [NSString stringWithFormat:@"tmp_%zd.jpg", i+1] : [NSString stringWithFormat:@"tmp_%zd.txt", i+1];
  162. [formData appendPartWithFileData:dataToUpload name:name fileName:fileName mimeType:mimeType];
  163. }
  164. } error:&error];
  165. }
  166. [request setValue:self.authorization ? self.authorization : ksEmptyString forHTTPHeaderField:@"Authorization"];
  167. [request setValue:self.homegrpId ? self.homegrpId : ksEmptyString forHTTPHeaderField:@"X-kneet-homegrp"];
  168. AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  169. op.responseSerializer = [AFHTTPResponseSerializer serializer];
  170. [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  171. [self finishRequest];
  172. NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  173. #ifndef PRODUCT_MODE
  174. NSLog(@"\n\nJSON=%@\n\n", JSONString);
  175. #endif
  176. NSError *error = nil;
  177. id rawJSON = [NSJSONSerialization JSONObjectWithData:responseObject
  178. options:NSJSONReadingAllowFragments
  179. error:&error];
  180. id JSONModel = nil;
  181. if (modelClass) {
  182. if ([rawJSON isKindOfClass:[NSArray class]]) {
  183. NSDictionary *JSONDic = @{@"list": rawJSON};
  184. JSONModel = [[modelClass alloc] initWithDictionary:JSONDic error:&error];
  185. } else {
  186. JSONModel = [[modelClass alloc] initWithString:JSONString error:&error];
  187. }
  188. } else {
  189. JSONModel = rawJSON;
  190. }
  191. if (error) {//오류 처리
  192. // JSONModel *result = [[JSONModel alloc] initWithString:JSONString error:nil];
  193. //
  194. // NSString *resultMsg = result.resultMsg ? result.resultMsg : MSG_ALERT_API_FAIL;
  195. // [[GWFacade facade] alert:resultMsg];
  196. JSONModel = nil;
  197. }
  198. //쿠키 설정
  199. NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[operation.response allHeaderFields] forURL:operation.request.URL];
  200. if (cookies && cookies.count > 0) {
  201. [self setCookies:cookies];
  202. }
  203. if (completion) {
  204. completion(JSONModel);
  205. }
  206. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  207. [self finishRequest];
  208. NSLog(@"HTTPStatus=%zd\n%@", operation.response.statusCode, error.localizedDescription);
  209. NSString *JSONString = [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];
  210. #ifndef PRODUCT_MODE
  211. NSLog(@"\n\nERROR=%@\n\n", JSONString);
  212. #endif
  213. JDErrorModel *jerror = [[JDErrorModel alloc] initWithString:JSONString error:&error];
  214. BOOL isLoginView = [[JDFacade facade].currentViewController isKindOfClass:[NSClassFromString(@"LoginViewController") class]];
  215. if (!isLoginView && [jerror.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_TOKEN]) {//인증토큰이 만료된 경우, 로그인 이동
  216. [[JDFacade facade] gotoLoginViewWithExpiring];
  217. } else if ([jerror.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_HOME]) {//홈그룹 아이디가 만료된 경우, 로그인 이동
  218. [[JDFacade facade] checkDefaultHome];
  219. } else if (failure && jerror) {
  220. failure(jerror);
  221. }
  222. }];
  223. [[NSOperationQueue mainQueue] addOperation:op];
  224. }
  225. #pragma mark - 동기 API 요청
  226. - (id)sendSyncRequestAPIPath:(NSString *)apiPath method:(NSString *)method parameters:(NSDictionary *)parameters modelClass:(Class)modelClass showLoadingView:(BOOL)showLoadingView {
  227. if (showLoadingView) {
  228. [self sendRequest];
  229. }
  230. NSString *rootPath = API_ROOT_PATH;
  231. NSString *pathURL = [self URLEncodedString:[NSString stringWithFormat:@"%@%@%@", kAPIServer, rootPath, apiPath]];
  232. NSLog(@"PATH=%@", pathURL);
  233. NSLog(@"PARAM=%@", parameters);
  234. NSError *error = nil;
  235. NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:pathURL parameters:parameters error:&error];
  236. [request setHTTPMethod:method];
  237. [request setTimeoutInterval:kDefaultTimeOut];
  238. [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  239. [request setValue:@"en" forHTTPHeaderField:@"Accept-Language"];
  240. [request setValue:self.authorization ? self.authorization : ksEmptyString forHTTPHeaderField:@"Authorization"];
  241. [request setValue:self.homegrpId ? self.homegrpId : ksEmptyString forHTTPHeaderField:@"X-kneet-homegrp"];
  242. AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  243. op.responseSerializer = [AFHTTPResponseSerializer serializer];
  244. [op start];
  245. [op waitUntilFinished];
  246. // Must call responseObject before checking the error
  247. id responseObject = [op responseObject];
  248. if (showLoadingView) {
  249. [self finishRequest];
  250. }
  251. if (error) {
  252. return nil;
  253. }
  254. NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  255. #ifdef DEBUG
  256. NSLog(@"\n\nJSON=%@\n\n", JSONString);
  257. #endif
  258. id rawJSON = [NSJSONSerialization JSONObjectWithData:responseObject
  259. options:NSJSONReadingAllowFragments
  260. error:&error];
  261. id JSONModel = nil;
  262. if (modelClass) {
  263. if ([rawJSON isKindOfClass:[NSArray class]]) {
  264. NSDictionary *JSONDic = @{@"list": rawJSON};
  265. JSONModel = [[modelClass alloc] initWithDictionary:JSONDic error:&error];
  266. } else {
  267. JSONModel = [[modelClass alloc] initWithString:JSONString error:&error];
  268. }
  269. } else {
  270. JSONModel = rawJSON;
  271. }
  272. return JSONModel;
  273. }
  274. - (id)sendSyncPostRequestAPIPath:(NSString *)apiPath parameters:(NSDictionary *)parameters modelClass:(Class)modelClass showLoadingView:(BOOL)showLoadingView {
  275. return [self sendSyncRequestAPIPath:apiPath method:ksHTTPRequestPOST parameters:parameters modelClass:modelClass showLoadingView:showLoadingView];
  276. }
  277. - (id)sendSyncGetRequestAPIPath:(NSString *)apiPath parameters:(NSDictionary *)parameters modelClass:(Class)modelClass showLoadingView:(BOOL)showLoadinView {
  278. return [self sendSyncRequestAPIPath:apiPath method:ksHTTPRequestGET parameters:parameters modelClass:modelClass showLoadingView:showLoadinView];
  279. }
  280. #pragma mark - Cookies
  281. - (void)setCookies:(NSArray *)cookies {
  282. NSMutableDictionary* cookieDict = [NSMutableDictionary new];
  283. for(NSHTTPCookie* cookie in cookies){
  284. [cookieDict setValue:cookie.properties forKey:cookie.name];
  285. }
  286. //쿠키 설정
  287. NSHTTPCookie *localCookie = [NSHTTPCookie cookieWithProperties:cookieDict];
  288. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:localCookie];
  289. }
  290. #pragma mark - Singleton
  291. + (RequestHandler *)handler {
  292. static RequestHandler *sharedRequestHandler = nil;
  293. static dispatch_once_t onceToken;
  294. dispatch_once(&onceToken, ^{
  295. sharedRequestHandler = [[self alloc] init];
  296. });
  297. return sharedRequestHandler;
  298. }
  299. - (id)init {
  300. if (self = [super init]) {
  301. }
  302. return self;
  303. }
  304. @end