Webpage loading via UIWebView with POST parameters

Can I load a page through a UIWebView with POST options? Maybe I can just load the inline form with the parameters and fill them with javascript and force them to submit, but is there a cleaner and faster way?

Thank!

+46
iphone uiwebview
Jul 17 '09 at 10:47
source share
4 answers

Create a POST URLRequest and use it to populate the 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]; 
+103
Jul 17 '09 at 12:37
source share

For swift

The following is an example of a POST call for a web view with content type x-www-form-urlencoded.

 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) 

You need to change postData for other types of content.

+9
Feb 17 '16 at 15:47
source share

The response from oxygen worked with a slight change. Using:

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

This did not work like GET or POST requests when adding a trailing slash to theURL . She worked.

 NSString *theURL = @"http://your_url.com/sub/"; 
+7
Oct 30 '12 at 15:12
source share

This is a change of @ 2ank3th answer for Swift 3:

 let url = NSURL (string: "https://www.google.com") let request = NSMutableURLRequest(url: url! as 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.data(using: String.Encoding.ascii, allowLossyConversion: true)! as NSData request.httpBody = postData as Data webView.loadRequest(request as URLRequest) 
+1
May 16 '17 at 17:10
source share



All Articles