Read JSON content from UIWebView
I'm using a UIWebView to display a captcha. If the user enters the ca开发者_Python百科ptcha correctly, then the server returns 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 store that data and remove the UIWebView.
I was thinking of setting up a delegate to the UIWebView and use its webViewDidFinishLoad, but how do I get the content loaded?
You may want to look into defining a UIWebViewDelegate
and using
webView:shouldStartLoadWithRequest:navigationType:
to intercept the request and handle it.
In your case, you would evaluate the NSURLRequest
and return NO
to prevent the WebView from loading. In turn, you would create a separate NSURLConnection
with the same request, and set up a delegate to receive the (JSON) response.
I came up with this (perhaps not so beautiful) solution:
Instead of returning a json-only response, I use the same HTML template that I used for the captcha. If the captcha succeeds, I send the json I want to the HTML template, which 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 contents in webViewDidFinishLoad by 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
}
Generally I think it was pretty easy and straight forward to implement.
精彩评论