Loading a webpage through UIWebView with POST parameters

Is it possible to load a page through UIWebView with POST parameters? I can probably just load an embedded form with the parameters and fill them in with javascript and force a submit, but is there a cleaner and faster way?

Thanks!


Create POST URLRequest and use it to fill webView

NSURL *url = [NSURL URLWithString: @"http://your_url.com"];
NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];

Below are examples for POST call for web view with content type x-www-form-urlencoded.

You need to change postData for other content types.

For Swift 3

let url = NSURL (string: "https://www.google.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let post: String = "sourceId=44574fdsf01e-e4da-4e8c-a897-17722d00e1fe&sourceType=abc"
let postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!

request.HTTPBody = postData
webView.loadRequest(request)

For Swift 4

let url = URL (string: "let url = NSURL (string: "https://www.google.com")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let post: String = "sourceId=44574fdsf01e-e4da-4e8c-a897-17722d00e1fe&sourceType=abc"
let postData: Data = post.data(using: String.Encoding.ascii, allowLossyConversion: true)!

request.httpBody = postData
webView.load(request as URLRequest)

The answer from oxigen worked with a minor change. When using:

NSString *theURL = @"http://your_url.com/sub";
...//and later
[request setURL:[NSURL URLWithString:theURL]];

It did not work, neither as GET or POST requests, when added a ending slash to the theURL it worked.

NSString *theURL = @"http://your_url.com/sub/";