Как внедрить файл JS для взаимодействия с PWA в Swift - PullRequest
0 голосов
/ 27 сентября 2019

В быстрый проект iOS я добавил файл JS.И используя WKWebview,

мой вопрос,

В iOS нам нужно написать? Как мы можем внедрить это?

const JSInterface = {
alertMe: (text) => {
    alert(text + '-> in hello.js');
}
}

ДоЯ написал функции в файле JS, как;

function alertMe(text) {
    alert(text + '-> in hello.js');
}

и ввел JS

func loadJavaScript() {

        self.jsContext = JSContext()

        if let jsScript = jsScriptText(){

            //Add an exception handler.
            self.jsContext.exceptionHandler = { context, exception in
                if let exc = exception {
                    print("JS Exception:", exc.toString())
                    self.webViewPWA.evaluateJavaScript("showToast(\(exc.toString() ?? ""))", completionHandler: { (result, error) in
                        guard error == nil else {
                            print("Script Error --> \(String(describing: error))")
                            return
                        }
                    })
                }
            }

            ///Inject 'user script' to WebPage
            let userScript = WKUserScript(source: jsScript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
            webViewPWA.configuration.userContentController.addUserScript(userScript)
            _ = jsContext?.evaluateScript(jsScript)
        }
    }


    func jsScriptText() -> String? {
            guard let jsPath = Bundle.main.path(forResource: "JSInterface", ofType: "js") else { return nil }
            debugPrint("\n ** \n JS Path --> \(jsPath)")
            do{
                let jsScript = try String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)
                return jsScript
            }catch{
                debugPrint("Error")
                return nil
            }
        }
...