Complex URL connection

Previously, I posted how you can create a simple URL connection to something easy, say a UIWebView.  Let’s look at a more advanced example of making an HTTPS call from a button click and then parsing the response.

You can do this however you want of course, but for simplicity, let’s just work with an HTTPS call returning a HTML response.

Oh and a couple of notes:
– Let’s do this asynchronously so as to not hang up any main threads
– Let’s go ahead and demonstrate a POST while we’re at it
– Let’s define something to hold the URL response data

//something like this or however you choose to define it
@property (strong) NSMutableData *ReceivedData;
@synthesize ReceivedData = receivedData;

1. Let’s say in your Interface Builder, you have a button that responds to a click. Let’s say the name of the method is MyButtonClick. The code in here is very self-explanatory. You’ll notice in the code though that we’ve made ourselves, self, the delegate to response to the callbacks. Those methods will be provided following this piece of code.

- (IBAction)MyButtonClick:(UIButton *)sender {
    
    NSLog(@"Looking up information...");

    NSURL *aUrl = [NSURL URLWithString:@"https: your url goes here"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl]; 
    [request setHTTPMethod:@"POST"]; 

    NSMutableString *myInputValuesPostString = [NSMutableString stringWithString:@"myemail="];
    [myInputValuesPostString appendString:[myUserObject myEmailAddress]];
    NSString *postString = [NSString stringWithString:myInputValuesPostString];   

    NSLog(@"%@", postString);       
        
    NSData *myRequestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    [request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request addValue:[NSString stringWithFormat:@"%i", [myRequestData length]] forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:myRequestData];
        
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 
        
    if (theConnection) {
        receivedData = [NSMutableData data];
        NSLog(@"Connection succeeded");
    } else {
        NSLog(@"Connection failed");
    }
}

2. Here’s your callbacks you’ll want to listen to

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    NSLog(@"didReceiveResponse called");
    [receivedData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSLog(@"didReceiveData called");
    [receivedData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failed! Error - %@ %@", 
          [error localizedDescription], 
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"Connection succeeded! Received %d bytes of data",[receivedData length]); 
    NSString *responseText = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@", responseText);
}
Advertisements
Leave a comment

4 Comments

  1. Jinu Kurian

     /  01/14/2013

    how do we append more than 1 parameters in the url string while POST’ing values in REST service call

    Reply
    • Jinu,

      Great question, thanks for asking. I believe this is what you are looking for…let me know if not.

      Create a NSMutableString and append the parameters to it. You’ll want to scrub the user input on both the client side and the server side, neither of which is shown here for simplicity. However, you should get a clear idea from this pseudocode (using the ampersand to precede the second parameter as you would expect).

          NSMutableString *myInputValuesPostString = [NSMutableString stringWithString:@"jobTitle="];
          [myInputValuesPostString appendString:[_jobTitle text]];
          [myInputValuesPostString appendString:@"&jobDetails="];
          [myInputValuesPostString appendString:[_jobDetails text]];
      

      Thanks.

      Scott

      Reply
  1. Working with JSON in iOS « aboutss
  2. Teleporting a Kangaroo « about ss

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: