iOS: Programmatically Posting to HTTP and Webview

When working with mobile apps there may come a time when you need to hook your native app up to a webview.  All-in-all this is a fairly simple process but as with anything there is always a gotcha lurking around the corner.

The first snippet of code is going to show you how to make a post request in iOS using NSURLConnection.  The first thing you will want to do is set your viewcontroller as the delegate for NSURLConnection in your header file like so:

1
@interface ViewController : UIViewController <NSURLConnectionDelegate>

Typically you would then implement the delegate methods but since it would make the most sense to show you how we get to those delegate methods, I will show you that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSString *post = [NSString stringWithFormat: @"userName=%@&password=%@", self.userName, self.password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:@"http://www.theurltopostto.com"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setTimeoutInterval:20.0];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];

As you can see, we simply create a new NSMutableURLRequest and set the parameters for that request specifying a post.  Then after it is all set up we simply create a new NSURLConnection.  This is what will then call our delegate methods as this is the asynchronous way of making the HTTP callout.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //Now you can do what you want with the response string from the data
    NSString* respsoneString = [NSString stringWithUTF8String:[_responseData bytes]];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //Do something if there is an error in the connection
}

As you can see we are just appending the data as we receive it to NSMutableData instance variable.  Once we have the data you can convert it to a string or do whatever you need for the situation.

Now let’s say you want to do the same thing only throw the results into a webview.  Using our last example, we would essentially log the user in and bring them to the site after login.  This is done in almost the exact same way except instead of using NSURLConnection we use the webview.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSString *post = [NSString stringWithFormat: @"userName=%@&password=%@", self.userName, self.password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:@"http://www.theurltopostto.com"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setTimeoutInterval:20.0];
[request setHTTPBody:postData];
[self.webViewMain loadRequest: request];

As you can see, it is exactly the same changing the last line of code.  This will log our user in and bring them to the appropriate page in the webview.

Like always, if you have any questions or comments, leave them below!

This entry was posted in Technology and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>