Advertisement
thieumao

NetworkConnection.m

Jun 23rd, 2016
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #import "NetworkConnection.h"
  2.  
  3. @implementation NetworkConnection
  4.  
  5. + (NSString *)formatMethodTypeToString:(METHODS)method {
  6.     NSString *result;
  7.     switch(method) {
  8.         case GET:
  9.             result = @"GET";
  10.             break;
  11.         case POST:
  12.             result = @"POST";
  13.             break;
  14.         case PATCH:
  15.             result = @"PATCH";
  16.             break;
  17.         case DELETE:
  18.             result = @"DELETE";
  19.             break;
  20.     }
  21.     return result;
  22. }
  23.  
  24. + (void)responseWithUrl:(NSString *)url
  25.                  method:(METHODS)method
  26.                  params:(NSString *)params
  27.           resultRequest:(ResultRequest)complete {
  28.     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  29.     if (method == GET) {
  30.         // GET method
  31.         [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",url,params]]];
  32.     } else {
  33.         // POST, DELETE, PATCH method
  34.         [request setURL:[NSURL URLWithString:url]];
  35.         NSData *postData = [params dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  36.         NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)postData.length];
  37.         [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  38.         [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  39.         request.HTTPBody = postData;
  40.     }
  41.     request.HTTPMethod = [self formatMethodTypeToString:method];
  42.     NSURLSession *session = [NSURLSession sharedSession];
  43.     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  44.         NSDictionary *dic;
  45.         if (data) {
  46.             dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
  47.         }
  48.         if (complete) {
  49.             complete(dic, error);
  50.         }
  51.     }];
  52.     [dataTask resume];
  53. }
  54.  
  55. + (void)cancelRequest {
  56.    // how to canncel response
  57. }
  58.  
  59. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement