Reputation: 209
I am new to Swift/iOS and have been working on an app that calls Swift code from JavaScript. There are not as many tutorials online and a lot of them are from when Swift was still in beta. Anyway, I was getting an error on my code and I am unable to compile it and I was wondering if any one had any tips and best practices when it comes to calling swift code from JavaScript.
Here is my code
import UIKit
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
var contentController = WKUserContentController();
var userScript = WKUserScript(
source: "redHeader()",
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "callbackHandler"
)
var config = WKWebViewConfiguration()
config.userContentController = contentController
self.webView = WKWebView(frame: self.view.frame, configuration: config)
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html")!)
var req = NSURLRequest(URL: url!)
self.webView!.loadRequest(req)
}
func userContentController(userContentController: WKUserContentController!,didReceiveScriptMessage message: WKScriptMessage!) {
if(message.name == "callbackHandler") {
println("JavaScript is sending a message \(message.body)")
} }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The error is on class ViewController: UIViewController, WKScriptMessageHandler {
and it says
Type 'ViewController' does not conform to protocol 'WKScriptMessageHandler'.
Any help would be greatly appreciated.
Upvotes: 4
Views: 6186
Reputation: 3545
I note that your method userContentController
is:
func userContentController(userContentController: WKUserContentController!,
didReceiveScriptMessage message: WKScriptMessage!)
it should be:
func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
(no optionals ! in prototype).
If you need more help, please post your index.html
source file
Upvotes: 5