ApplicationWillTerminate - how do i run JS callback?

Hi everyone!

Ladies and gents, I am struggling with the issue for 2+ weeks in a raw, still stuck and I appreciate any help / advices / suggestions!

  • What I am dealing with: web page + backend (php), swift app (wkwebview + some native components).

  • What I am trying to achieve: I need to let the web page know my app is changing it's state, by executing some java scripts (one script for "enter background mode", another one for "enter foreground", and so on).

  • What is my issue: I can't handle the case of app termination. Whenever the user is killing the app by home-double-click/swipe up, ApplicationWillTerminate method from AppDelegate is being called, but it fails to execute webView.evaluateJavaScript from here, as far as I was able to understand - due to the closure / completion handler is has, for it is async by design. All other cases are covered, works fine, and with the last one for termination I am desperately stuck.

I am playing around with the following code:

func applicationWillTerminate(_ application: UIApplication) {
        if let callback = unloadListenerCallback {
            if callback == "" {
                debugPrint("got null callback - stop listening")
                unloadListenerCallback = nil
            }
            else {
                jsCallbackInjection(s: callback) //executing JS callback injection into WebView

            }
        }
    }

unloadListenerCallback is the string? variable, works as a charm in other cases (just to mention it for clarity). jsCallbackInjection is the function, also works perfectly elsewhere:

func jsCallbackInjection(s: String) {
        let jscallbackname = s
        HomeController.instance.webView?.evaluateJavaScript(jscallbackname) { (result, error) in
             if error == nil {
                 print(result as Any)
                 print("Executed js callback: \(jscallbackname)")
             } else {
                 print("Error is \(String(describing: error)), js callback is: \(jscallbackname)")
             }
         }
    }

My ask is:

  1. How do I made this code working, if possible? Any ideas, suggestions, tips or tricks?
  2. If not possible, any ideas on "how do I let my web counterpart know my app was terminated"? What do I do from here?

Many many thanks in advance!

ApplicationWillTerminate - how do i run JS callback?
 
 
Q