7

I was wondering if it were possible to grab POST data and save it when a submit button was pressed in a UIWebView. Should I be using javascript and adding eventlisteners so that I can get the values before the submit goes through? If so, how would I be able to get the data back to my code in obj c? Otherwise, is there any easier way? Thanks

bph
  • 189
  • 2
  • 14

1 Answers1

13

You need to implement the UIWebViewDelegate. There is a hook called "shouldStartLoadWithRequest" that gets called by iOS.

Psueudocode below.

@interface MyController<UIWebViewDelegate>
@end

@implementation MyController
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request       navigationType:(UIWebViewNavigationType)navigationType
{
    // do your magic
    NSData *data = request.HTTPBody; // contains the HTTP body as in an HTTP POST request.

    // return YES to continue to load the URL
}
@end
Ash
  • 156
  • 1
  • 3
  • Thanks, I was able to NSLog the data. However, if I also wanted the original text of the fields submitted, would I need javascript? – bph May 05 '12 at 01:37
  • I recommend passing the original text/label as a hidden form field and then extracting it just as a field in POST data. If you don't prefer that then you can use evaluate arbitrary javascript using [webView stringByEvaluatingJavaScriptFromString:@""]; – Ash May 05 '12 at 23:40
  • 6
    You can get the text of the POST data with the method... `[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]` – Nate Potter Aug 21 '12 at 23:20