How to send HTTP Request in iOS using NSURLConnection Objective-C

Total Post:159

Points:1117
iOS
 1025  View(s)
Ratings:
Rate this:
Hi Buddy

I am new in iOS .I want to register user through iOS app I have PHP webpage for registration process .I want send json data on my web page . How to send HTTP Request in iOS using NSURLConnection Objective-C .Please help I would really appreciate your help.

Thanks

  1. Post:45

    Points:323
    Re: How to send HTTP Request in iOS using NSURLConnection Objective-C

    Following is the Objective-C code to post json data in iOS -


    NSMutableDictionary *requestDictionary = [[NSMutableDictionary alloc]
    init];
    [requestDictionary setObject:@"Robert" forKey:@"firstName"];
    [requestDictionary setObject:@"Abraham" forKey:@"lastName"];
    [requestDictionary setObject:@"robertab1999@gmail.com" forKey:@"email"];
    [requestDictionary setObject:@"pass1234" forKey:@"password"];
    NSData *data = [NSJSONSerialization dataWithJSONObject:requestDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.51:82/test/handleRequest.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
    cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)jsonStr.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: data];
    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc]init];
    NSError*error = [[NSError alloc] init];
    //synchronous filling of data from HTTP POST response NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //convert data into string NSString*responseString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];
    NSLog(@"Response code %ld",(long)[response statusCode]);
    NSLog(@"Response String %@",responseString);

      Modified On Apr-11-2018 06:04:20 AM

Answer