Advertisement
thieumao

Json objective c demo

May 18th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #import "ViewController.h"
  2.  
  3. @interface ViewController ()
  4.  
  5. @end
  6.  
  7. @implementation ViewController
  8.  
  9. - (void)viewDidLoad {
  10.     [super viewDidLoad];
  11.    
  12.     NSString *post = [NSString stringWithFormat:@"name=%@&email=%@&password=%@&password_confirmation=%@",@"motmao",@"motmao@gmail.com",@"123456",@"123456"];
  13.     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  14.     NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
  15.    
  16.     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  17.     [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://manh-nt.herokuapp.com/users.json"]]];
  18.     [request setHTTPMethod:@"POST"];
  19.     [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  20.     [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
  21.     [request setHTTPBody:postData];
  22.     NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
  23.     if(conn)
  24.     {
  25.         NSLog(@"Connection Successful");
  26.     }
  27.     else
  28.     {
  29.         NSLog(@"Connection could not be made");
  30.     }
  31.    
  32. }
  33.  
  34.  
  35. // This method is used to receive the data which we get using post method.
  36. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
  37.     NSString* myString;
  38.     myString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
  39.     NSLog(@"%@",myString);
  40. }
  41.  
  42. // This method receives the error report in case of connection is not made to server.
  43. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {}
  44.  
  45. // This method is used to process the data after connection has made successfully.
  46. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {}
  47.  
  48. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement