向 WKWebView 发送数据

Send data to WKWebView

我正在创建一个显示本地网页的视图,该网页也有样式和 JavaScript(本质上是一个混合本机应用程序),我正在使用 WKWebView。

我知道如何将数据从 JavaScript 发送到本机代码,但不清楚如何以相反的方式进行。我想将使用本机 iOS 代码获取的 JSON 对象发送到我的 MKWebView。

我收到以下错误

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo=0x7bfb3c30 {NSLocalizedDescription=A JavaScript exception occurred}
    nil

下面是我的代码。

//
//  WebViewController.swift
//
//  Created by Adam Bulmer on 09/03/2015.
//  Copyright (c) 2015 Adam Bulmer. All rights reserved.
//

import Foundation
import WebKit

class WebViewController: BaseViewController, WKScriptMessageHandler, WKNavigationDelegate {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView!

    override func loadView() {

        super.loadView()

        var config = WKWebViewConfiguration();
        var contentController = WKUserContentController();

        var userScript = WKUserScript(
            source: "bootstrap()",
            injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
            forMainFrameOnly: true
        )

        contentController.addUserScript(userScript)
        config.userContentController = contentController;


        self.webView = WKWebView(frame:self.view.frame, configuration: config)
        self.webView.navigationDelegate = self;

        self.view = self.webView!

    }

    override func viewDidLoad() {

        super.viewDidLoad()

        var path = NSBundle.mainBundle().pathForResource(webViewName(),
            ofType: "html");

        var url = NSURL(fileURLWithPath: path!);
        var request = NSURLRequest(URL: url!);

        self.webView!.loadRequest(request);

    }

    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {

        var param = "Hello World";
        var exec_template = "test(\(param)');";

        self.webView!.evaluateJavaScript(exec_template, completionHandler: { (test, error) -> Void in
            println(error);
            println(test);
        })

    }

    func webViewName() -> String {
        return "";
    }

// MARK: WKScriptMessageHandler callback
// Delegate callback for when scripts sends message

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {

    }

}

此代码:

    var param = "Hello World";
    var exec_template = "test(\(param)');";

将导致..

test(Hello World');

.. 正在执行,这不是有效的 JS。您错过了代码中的开头 '