Advertisement
thieumao

Network

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