综合编程

Call the Swift function with javascript using UIWebview

微信扫一扫,分享到朋友圈

Call the Swift function with javascript using UIWebview
0

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>

Is this possible with a UIWebView? Thanks all!

Implement listenInSwift
like this:

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

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...')
    }
}

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

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)

阅读原文...


微信扫一扫,分享到朋友圈

Call the Swift function with javascript using UIWebview
0

Hello, buddy!

Python Software Foundation: Python Community service award Q3: Mario Corchero

上一篇

Augmented Reality Google Maps is coming, starts testing in private

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

Call the Swift function with javascript using UIWebview

长按储存图像,分享给朋友