I’m developing an iPhone app which has a built-in quiz which runs using JavaScript within a UIWebView. After a user clicks aCheck Answers button, I have to use JavaScript to determine if all the answers are correct, so I can save this result for later.
Here is the relevant JavaScript:
function checkAnswers() { // Do stuff to see if all answers were correct ... // Send all correct status back to Objective-C window.location = "/allCorrect/" + allCorrect; }
In Objective-C, you then need to set up a UIWebViewDelegate to intercept whenever a new URL is to be loaded into the UIWebView. Then you need to callshouldStartLoadWithRequest and if you called your fake URL, then it shouldn’t load, but execute the code you need to run in Objective-C instead. Here is the relevant Objective-C code:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if ( [request.mainDocumentURL.relativePath isEqualToString:@"/allCorrect/false"] ) { NSLog( @"Nope, that is not right!" ); return false; } if ( [request.mainDocumentURL.relativePath isEqualToString:@"/allCorrect/true"] ) { NSLog( @"You got them all!" ); return false; } return true; }
From: http://www.chucksmith.de/2009/04/send-bool-value-from-javascript-to-objective-c/
see also: http://iphoneincubator.com/blog/tag/uiwebview