Add Firebase Device Token to user authenticated in WebView

199 Views Asked by At

I am transforming a PWA to a native iOS application. To achieve this I have used pwabuilder.com.

The current impediment I am facing is the ability to receive FCM push-notifications on my native app. I have successfully implemented Firebase on my native app, but I am stuck on how to link the generated device token to the user of my app.

In the PWA using Javascript, I could just let Firebase generate the token and send a AJAX-request to my back-end to add the firebase token to the user in the active session.

The problem in the native app is that the Firebase Device Token is generated in the Swift-code, but my user authenticates himself in the WebView.

So I need a secure way to retrieve the authenticated user from Swift's Webview. Or I need a secure way to inject the Firebase Device Token into the webview, so I can use Javascript to send it to the server.

1

There are 1 best solutions below

0
O'Niel On

Solved. I my Javascript I had the following code:

function sendFirebaseToken(token) {
    let data = {
        "token": token,
    };

    let url = "/update-firebase-token";
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });
}

I can call this code when the token is received in Swift:

func sendDeviceTokenToWebView(token: String) {
    print("Sending device token to webview");
    func checkViewAndEvaluate() {
        if (!Hellofood.webView.isHidden && !Hellofood.webView.isLoading ) {
            DispatchQueue.main.async(execute: {
                Hellofood.webView.evaluateJavaScript("saveFirebaseTokenFromApp('\(token)')")
            })
        }
        else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                checkViewAndEvaluate()
            }
        }
    }
    checkViewAndEvaluate()
}