RequestHandler.m 17 KB

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