Lorenz Meyer
Lorenz Meyer

Reputation: 19905

Share text content on iOS causes the app to crash

I have an app that allows a user to share text from inside a webwiew.

The following code works on all devices I could test, but I have users that report that a click on the button in the webview closes the application consitently.

Javascript click handler:

function onClick() {
    let text = '...'
    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.shareText) {
        window.webkit.messageHandlers.shareText.postMessage(text)
    }
}

Swift ViewController:

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {
    var webView : WKWebView!

    func WKWebViewInit(){
        let configuration = WKWebViewConfiguration()
        let preferences = WKPreferences()
        preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        configuration.preferences = preferences

        let contentController = WKUserContentController();
        contentController.add(self, name: "shareText")
        configuration.userContentController = contentController;
        webView = WKWebView(frame: self.view.frame, configuration: configuration)
        webView.navigationDelegate = self
        webView.uiDelegate = self

        let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html") {
        webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
        self.view.addSubview(webView)
        self.view.sendSubviewToBack(webView)
    }        

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if (message.name == "shareText") {
            let items = [message.body]
            let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
            present(ac, animated: true)
        }
    }
}

Where is this code not sure, that means, where is it subject to make the application crash? Or maybe the reporting user's device has a more general problem?

Upvotes: 0

Views: 26

Answers (0)

Related Questions