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)
    }
}
Rohith R
  • 1,309
  • 2
  • 17
  • 36
  • Possible duplicate of [Call swift function with javascript using UIWebview](https://stackoverflow.com/questions/36139062/call-swift-function-with-javascript-using-uiwebview) – MGY Aug 23 '17 at 05:26
  • No. The link that you gave was for iOS. I wanted the code for Mac OS X. – Rohith R Aug 23 '17 at 06:05

1 Answers1

-1

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

Chris.W
  • 15
  • 3