UIWebView可以与应用程序进行交互(通信)吗?

Leo*_*tik 10 cocoa-touch objective-c ios

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

小智 24

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

window.location = "request_for_action://anything/that/is/a/valid/url/can/go/here";
Run Code Online (Sandbox Code Playgroud)

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

webView:shouldLoadWithRequest:navigationType
Run Code Online (Sandbox Code Playgroud)

喜欢的东西

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
}
Run Code Online (Sandbox Code Playgroud)

-

暂且不说,你可以做其他方式,让iOS代码通过使用来调用你的html中的一些JS代码

NSString* returnValue = [self.webView stringByEvaluatingJavaScriptFromString: "someJSFunction()"];
Run Code Online (Sandbox Code Playgroud)


mat*_*att 9

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

Web视图的委托已发送webView:shouldStartLoadWithRequest:navigationType:.你分析发生了什么,并按你的意愿做出回应.为了防止Web视图尝试跟踪链接(毕竟这可能是完全假的),只需返回NO.

在这个来自TidBITS新闻应用程序的示例中,我在网页中有一个使用完全构成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;
}
Run Code Online (Sandbox Code Playgroud)