10

我去使用 UIWebView 来显示动态内容,而不是使用 UI 元素在本地进行。是否可以通过简单地点击 UIWebView 内的链接来触发本机应用程序功能?示例:点击然后切换当前视图的链接?

4

3 回答 3

24

是的,这是可能的。在您的 html 中,您编写一个 JS 来加载一个带有虚假方案的 URL,例如

window.location = "request_for_action://anything/that/is/a/valid/url/can/go/here";

然后,在您的 iOS 代码中,为您的 webView 分配一个委托,并在您的委托中处理

webView:shouldLoadWithRequest:navigationType

有类似的东西

if( [request.URL.scheme isEqualToString: @"request_for_action"] )
{
   // parse your custom URL to extract parameter, use URL parts or query string as you like
   return NO; // return NO, so webView won't actually try to load this fake request
}

--

顺便说一句,你可以做另一种方式,让 iOS 代码通过使用调用 html 中的一些 JS 代码

NSString* returnValue = [self.webView stringByEvaluatingJavaScriptFromString: "someJSFunction()"];
于 2013-04-13T03:22:46.817 回答
9

是的!当用户按下链接时,您会在 Web 视图的委托中听到它,然后可以做任何您想做的事情。强大的东西可以通过这种方式完成。

发送 Web 视图的委托webView:shouldStartLoadWithRequest:navigationType:。你分析发生了什么,并随心所欲地做出回应。为了防止 web 视图试图跟随链接(这可能完全是假的,毕竟),只需返回 NO。

在这个来自 TidBITS News 应用程序的示例中,我在网页中有一个链接,该链接使用了一个完全虚构的play:方案。我在委托中检测到这一点并播放:

- (BOOL)webView:(UIWebView *)webView
        shouldStartLoadWithRequest:(NSURLRequest *)r
        navigationType:(UIWebViewNavigationType)nt {
    if ([r.URL.scheme isEqualToString: @"play"]) {
        [self doPlay:nil];
        return NO;
    }
    if (nt == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:r.URL];
        return NO;
    }
    return YES;
}
于 2013-04-13T03:15:25.193 回答
2

实现UIWebViewDelegate方法webView:shouldStartLoadWithRequest:navigationType:

根据需要处理 navigationType 和请求。

于 2013-04-13T03:15:59.023 回答