this is my very first project in swift and yes I've see that there are similar question about this topic already around and I've read almost all but I still can't get my code working.
I've a class that implements the WKScriptMessageHandler
protocol to provide a bridge between iOS and the hosted javascript in a WKWebView
.
Among the parameters passed from javascript (interpreted as NSDictionary
), I have one named _method
that contains the swift method name that javascript wants to invoke.
Metod name is extracted successfully on swift side and then I try to call it by using a Selector
and here is where I fail:
class AppScriptMessageHandler: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let dict = message.body as! NSDictionary;
let method = dict.value(forKey: "_method") as? String ?? "";
let selector = Selector(method); // method = "getDocumentsFolder"
let ret = perform(selector)?.takeUnretainedValue()
print(ret!)
}
func getDocumentsFolder() -> String {
return "Pippo"
}
}
All goes fine until I try to do let ret = perform(selector)
. Here I get the following runtime error:
2018-02-27 15:49:37.279730+0100 wktest[8375:198645] *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[wktest.AppScriptMessageHandler getDocumentsFolder]: unrecognized selector sent to instance 0x604000019ef0'
Where I do wrong? I've also tried appending :
to method
but I still get same error
Thanks in advance for any help!