Swift 中的 Webview 管理

Posted

技术标签:

【中文标题】Swift 中的 Webview 管理【英文标题】:Webview manage in Swift 【发布时间】:2017-03-22 18:41:05 【问题描述】:

我在 Swift 3 中制作应用程序 enter image description here重定向网页视图后首先登录我的应用程序。如果我单击网页视图页面中的注销按钮,我想重定向回我的应用程序。我该怎么做?

【问题讨论】:

你有什么尝试——你是如何显示这个网页视图的? 带 loadRequest 方法 当然,但是您有一个显示 web 视图(或其他东西)的视图控制器? 当然是 WebViewController 我现在的 webview 我在网站上登录后输入用户名和密码我的应用程序 在这种情况下,请使用 UIWebViewDelegate 从您的 web 视图中调用本机(Swift 或 Obj-C)函数/方法。 ***.com/a/15541607/1313761 【参考方案1】:

您可以使用WKScriptMessagejavascript 来回调您的viewController 并执行本机代码。

在您的视图控制器中:

//MARK: WKScriptMessageHandler (callback from js in html file)
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
    if message.name == "callbackHandler" 
        print(message.body)

        //My function
        if (message.body as AnyObject).contains("myFunctionName")
            self.playVideo()
        
    

在您的 HTML 文件中:

<!-- JS for Native Application Callbacks -->
<script type="text/javascript">
    function callNativeApp () 
        //ios
        try 
            window.webkit.messageHandlers.callbackHandler.postMessage("myFunctionName");
         catch(err) 
            console.log('The native context does not exist yet');
        
    
</script>

【讨论】:

以上是关于Swift 中的 Webview 管理的主要内容,如果未能解决你的问题,请参考以下文章