0

I am launching a web-view from my swift app. From the web-view I want to call a swift function on a button click. I found the code sample here.

When I press the button, nothing happens. The URL I am loading in the web-view is https://test-swift-js.github.io

Here is the code :

import Cocoa
import WebKit

class ViewController : NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    var webView:WebView!

    @IBAction func mybutton(_ sender: Any) {
        let url = URL(string: "https://test-swift-js.github.io")
        let request = URLRequest(url: url!)
        webView =  WebView(frame: NSRect(x: 0, y: 0, width: 1000, height: 1000))
        webView.mainFrame.load(request)
        self.view.addSubview(webView)
    }

    func webView(webView: WebView!, didClearWindowObject windowObject: WebScriptObject!, forFrame frame: WebFrame!) {
        windowObject.setValue(self, forKey: "interOp")
    }

    //The name used to represent the Swift function name in Javascript.
    class func webScriptNameForSelector(aSelector: Selector) -> String!
    {
        if aSelector == "callSwift:"
        {
            return "callSwift"
        }
        else
        {
            return nil
        }
    }
    class func isSelectorExcludedFromWebScript(aSelector: Selector) -> Bool
    {
        return false
    }
    func callSwift(message:String)
    {
        var alert = NSAlert()
        alert.messageText = message
        alert.alertStyle = NSAlertStyle.informational
        alert.beginSheetModal(for: self.view.window!, completionHandler: nil)
    }
}
2

1 Answer 1

-1

Maybe you forget to set the delegate. enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.