Open Url hosted using POST method in Safari using sharedApplication openURL method

taus-iDeveloper picture taus-iDeveloper · Nov 2, 2012 · Viewed 13.4k times · Source

I have a situation in which I am using a POST method to host a URL in the safari browser in the simulator. The web page is opened in safari after launching my iOS app in the simulator. To launch safari i have used [[UIApplication sharedApplication] openURL: ...

The post method is as follows:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://***some client url***.jsp"]];

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@", userName, password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];`


NSURLConnection* _urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_urlConnection start];

this piece of code works fine when using UIWebView. But i want to launch Safari using this "request" which has appended username & password data from the POST method.

To launch Safari i must call this code:

[[UIApplication sharedApplication] openURL:request];

But this throws a warning obviously because "request" is of type NSMutableURLRequest. "Semantic Issue: Incompatible pointer types sending 'NSMutableURLRequest *' to the parameter of type 'NSURL *"...

I cannot even use [[UIApplication sharedApplication] openURL:request.URL]; since this will give me the URL which is not appended with username & password(with out POST method).

I want to know how to typecast/convert this request(NSMutableURLRequest) so that I can accommodate it in the [[UIApplication sharedApplication] openURL...

Hope i am quite clear with my question. Any help will be highly appreciated. Thanks in advance !!

Answer

iDev picture iDev · Nov 11, 2012

The recommended approach is to use UIWebView in your application and create post request using NSURLRequest and NSURLConnection. It is pretty easy to create a post request and fire the request. Since you have already figured this out and you dont want to use this approach, only alternative is by creating a temporary html file as mentioned here. You can try with the approach they are following and check if it is working in your case.

As per that link, you have to write a temporary html file. This html file will have an onLoad() javascript which immediately sends the POST, and a button for users that don't have javascript enabled. You can create NSURL object as [NSURL fileURLWithPath:path]; from this file.

Another solution is by creating a one time key from the webserver and pass it to safari via HTTPS request as mentioned here.