RequestHandler.m 18 KB

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