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