Call swift function with javascript using UIWebview

前端 未结 2 1937
天命终不由人
天命终不由人 2020-12-17 06:45

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 swif

相关标签:
2条回答
  • 2020-12-17 06:56

    this worked fine for me:

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.scheme == "com.example.app" {
            print("I’m some JavaScript hoho")
        }
    
        return true
    }
    

    Note: you have to add "com.example.app" or whatever in your xcode project settings. Go to info, scroll down and find URL Scheme. Add your desired scheme there. Leave the other stuff the way it is. Then it should work just fine.

    0 讨论(0)
  • 2020-12-17 07:14

    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)
    
    0 讨论(0)
提交回复
热议问题