使用 UIWebview 使用 javascript 调用 swift 函数

2023-10-21移动开发问题
3

本文介绍了使用 UIWebview 使用 javascript 调用 swift 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果有人问过这个问题,我深表歉意,但我找不到任何答案或解决方案.我希望从UIWebView"调用一个 JavaScript 函数并迅速收听它.我发现的任何示例都使用WKWebView".必须有一种简单的方法来监听 JavaScript 函数,如下所示:

I apologize if this has been asked but I was unable to find any answer or solution. I am looking to call a JavaScript function from a "UIWebView" and listen for it in swift. Any example I have found uses "WKWebView". There has to be an easy way to listen to a JavaScript function like the below:

// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>

这可以通过 UIWebView 实现吗?谢谢大家!

Is this possible with a UIWebView? Thanks all!

推荐答案

像这样实现 listenInSwift:

function listenInSwift() {
    window.location = 'yoururlscheme://somehost?greeting=hello'
} 

然后在您的 UIWebViewDelegate 类中使用此代码侦听此 URL:

Then listen for this URL with this code in your UIWebViewDelegate class:

func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
    if request.URL.scheme == 'yoururlscheme' {
        print('Hello JavaScript...')
    }
}

不要忘记在 Xcode 中注册您的 URL Scheme(在本例中为yoururlscheme").

Don't forget to register your URL Scheme (in this case 'yoururlscheme') in Xcode.

要在 web 视图中加载本地文件,试试这个:

To load a local file in the web view, try this:

let baseURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath);
let relativePath = "www/(file)"
let fileURL = NSURL(string: relativePath, relativeToURL: baseURL);
let URLRequest = NSURLRequest(URL: fileURL!);
webView.loadRequest(URLRequest)

这篇关于使用 UIWebview 使用 javascript 调用 swift 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

突出显示朗读文本(在 iPhone 的故事书类型应用程序中)
Highlight Read-Along Text (in a storybook type app for iPhone)(突出显示朗读文本(在 iPhone 的故事书类型应用程序中))...
2024-08-12 移动开发问题
9

正确的 cocos2d 场景重启?
Proper cocos2d scene restart?(正确的 cocos2d 场景重启?)...
2024-08-12 移动开发问题
7

cocos2D iPhone中的UItextfield文本对齐问题
UItextfield text alignment issue in cocos2D iPhone(cocos2D iPhone中的UItextfield文本对齐问题)...
2024-08-12 移动开发问题
7

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9

如何在使用 cocos2d 的 iphone 应用程序中使用 MYSQL 数据库连接?
How can i use MYSQL database connection in iphone application useing cocos2d?(如何在使用 cocos2d 的 iphone 应用程序中使用 MYSQL 数据库连接?)...
2024-08-12 移动开发问题
5