Making HTTP Requests in iOS

stringWithContentsOfURL

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
  NSError *error = nil;
  NSURL *nsurl = [NSURL URLWithString:YOUR_URL_STRING];
  NSString *responseString = [NSString stringWithContentsOfURL:nsurl
                                       encoding:NSUTF8StringEncoding
                                       error:&error];
  if (!error) {
    id result = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];

    NSLog(@"JSON: %@", [result objectForKey:@"result"]);
  }
});

NSURLConnection

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: @"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSError *error;
id result = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
NSLog(@"JSON: %@",[result objectForKey:@"result"]);

NSURLSession

// URL of the endpoint we're going to contact.
NSURL *url = [NSURL URLWithString:@"http://xxx.ooo.com/app/api/register.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
#ifdef JSON_REQUEST
// Create a simple post dictionary.
NSDictionary *postDictionary = @{
                                  @"Mobile": @"0933123456",
                                  @"Email": @"aa@bb.cc"
                                };
// Convert the dictionary into JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:postDictionary
                                                   options:0
                                                     error:nil];
// Create a POST request with our JSON as a request body.
request.HTTPMethod = @"POST";
request.HTTPBody = JSONData;
#endif
#ifdef URL_FORM_REQUEST
NSString *postString = [NSString stringWithFormat:@"Mobile=%@&Email=%@",@"0933123456", @"aa@bb.cc"];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];
request.HTTPBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
#endif
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  if (!error) {
    NSLog(@"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSLog(@"name: %@", [result objectForKey:@"Success"]);
  }
  else {
    NSLog(@"Error: %@", error.localizedDescription);
  }
}];
// Start the task.
[task resume];