RequestHandler.m 18 KB

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