从当前的UIWebview中读取html

时间:2013-07-11 10:26:34

标签: javascript ios uiwebview

我有一个显示一些链接的UIWebview。当我在链接上clic时,它会向我发送一些JSON。为了显示发送给我的数据,我需要:

1)检测何时调用链接

2)获取json

对于2),我尝试过[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];让我回复:

<pre style="word-wrap: break-word; white-space: pre-wrap;">{some JSON}</pre>

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"pre\")"];返回一个空对象。我有什么其他方式来获取我的JSON?

对于1)是否有一个UIWebView委托方法来检测链接何时被调用?

2 个答案:

答案 0 :(得分:4)

我有同样的问题。我用这个代码解决了

    NSString *jsonString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"pre\")[0].innerHTML"];

答案 1 :(得分:0)

iOS开发者库是您最好的朋友。事实证明,UIWebView确实有一个您可以订阅的协议。 以下是委托回调的链接:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIWebViewDelegate

你想要的是

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

实施此协议方法,您可以内省NSURLRequest对象的NSURL,然后其余的由您决定......

编辑: 为了完整起见,我应该在- (NSData *)HTTPBody个对象上提到NSURLRequest实例方法。你最有可能在那块NSData中找到JSON。 Foundation框架中有一个NSJSONSerialization类,您可以使用它来创建JSON数据中的NSObject。 这是你到目前为止所拥有的......

// UIWebView delegate method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSData *jsonData = request.HTTPBody;
  id jsonObj = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: nil];
  // do stuff with the object...
  ...
  // the webview shouldn't load the request since it's going to be raw json data (or is it)
  return NO;
}

理论上,只有当您收到的JSON数据是纯JSON时,此代码才有效。从您的问题来看,似乎有一些HTML附加到JSON数据,因此您必须实现一个方法来剥离它的HTML部分的数据。在以这种方式转换数据结构时要小心,有很多细则。查看NSJSONSerialization文档以获取更多具体信息: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

快乐的编码!