Reading JSON content from UIWebView
I am using UIWebView to display captcha. If the user enters the captcha correctly, the server returns the data using JSON serialization. I don't want the view to display this, instead I want to intercept the loads of the UIWebView, and if it returns JSON serialized data, I want to keep that data and delete the UIWebView.
I was thinking about setting up a delegate in UIWebView and using its webViewDidFinishLoad, but how do I load the content?
source to share
You can look at the definition UIWebViewDelegate
and use
webView:shouldStartLoadWithRequest:navigationType:
it to intercept the request and process it.
In your case, you can evaluate NSURLRequest
and revert NO
to prevent the WebView from loading. In turn, you create a separate one NSURLConnection
with the same request and set up a delegate to receive the response (JSON).
source to share
I came up with this (maybe not very pretty) solution:
Instead of returning a json-only response, I am using the same HTML template I used for captcha. If the captcha is successful, I will post the json, I want an HTML template that displays it in a hidden div with an id:
<html>
<body>
{% if captcha_success %}
<div id="json" style="display: none">{"jsonvalue":"{{result}}"}</div>
{% else %}
// display captcha as usual
{% endif %}
</body>
</html>
and then I can get the content in webViewDidFinishLoad using:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *res = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('json').innerHTML"];
NSDictionary *json = [[CJSONDeserializer deserializer] deserializeAsDictionary:[res dataUsingEncoding:NSUTF8StringEncoding] error:nil];
// more stuff
}
All in all, I think it was pretty easy and straightforward to implement.
source to share