khmyznikov / ios-pwa-wrap

Makes possible of publishing PWA to Apple Store like TWA from Google.
The Unlicense
161 stars 14 forks source link

How to get firebase token for fcm #2

Open gaza1994 opened 3 years ago

gaza1994 commented 3 years ago

Hi great work on this project!

Question: After requesting push notification permissions, im assuming we get a FCM token from Google ... is there any way we can send this back to the website so it can be handled and stored in a database? I've looked through the code but cant seem to figure out a way to do this.

khmyznikov commented 3 years ago

We are working by Topics, so that's why I don't implement token share. You can make something like this PWAShell.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: token }))") and catch this on web side.

bruno-delfim commented 1 year ago

Hi, I'm needing the id of the token to save in the database. In which file do I need to add this code? PWAShell.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: token }))")

And how would you get it in javascript?

Thanks. Great job.

gareth-johnstone commented 1 year ago

Hi, I'm needing the id of the token to save in the database. In which file do I need to add this code? PWAShell.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: token }))")

And how would you get it in javascript?

Thanks. Great job.

I managed it by listening for the event getting triggered in the js code and can pick up on the fcm token from there

bruno-delfim commented 1 year ago

@gareth-johnstone could you please put a code example on the frontend to get the token?

gareth-johnstone commented 1 year ago

@gareth-johnstone could you please put a code example on the frontend to get the token?

window.addEventListener('FCM-token-handle', function (message) { console.info(message) // intentionally left in /* FCM token is returned as "Optional(\"<TOKEN>\")" So just tidying it up with some regex so its useable. */ var fcmToken = message.detail.match(/\"(.*?)\"/)[0].replace(/\"/g, '')

Not the full snippet, copy paste from my phone 😂 but you get the idea

bruno-delfim commented 1 year ago

Hi @gareth-johnstone,

I need help please, I'm not getting it. In the frontend I was able to trace the event, but it has the error when loading the token.

I made the firebase settings, and changed some swift files. https://firebase.google.com/docs/cloud-messaging/ios/client?authuser=0&hl=pt#swift_4

Frontend:

if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers['FCM-token-handle']) {
      window.iosFcmTokenHandle = true;
    }
pushPermissionRequest = function(){
      if (window.iOSPushCapability) window.webkit.messageHandlers['push-permission-request'].postMessage('push-permission-request');
      if (window.iosFcmTokenHandle) window.webkit.messageHandlers['FCM-token-handle'].postMessage('FCM-token-handle');
    }
    pushPermissionRequest();

// Get the FCM token
    window.addEventListener('FCM-token-handle', (token) => {
      alert('FCM-token-handle...');
      alert(token.detail);
    });

In the project folder, I changed the following files: WebView.swift userContentController.add(WKSMH, name: "FCM-token-handle")

ViewController.swift

if message.name =="FCM-token-handle" {
     handleFCMToken()
   }

PushNotifications.swift

func handleFCMToken(){
  DispatchQueue.main.async(execute: {
     Messaging.messaging().token { token, error on
        if let error = error {
          print("Error fetching FCM registration token: \(error)")
          PWAapp.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: 'ERROR GET TOKEN' }))")
       } else if let token = token {
         print("FCM registration token: \(token)")
         PWAapp.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: token }))")
       }
    }

  })
}

After running the event, it always falls on ERROR GET TOKEN, what am I doing wrong?

bruno-delfim commented 1 year ago

We are working by Topics, so that's why I don't implement token share. You can make something like this PWAShell.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: token }))") and catch this on web side.

Could you please provide a tutorial on how to do this? I need only the device id.

igor-shyrnin commented 1 year ago

We are working by Topics, so that's why I don't implement token share. You can make something like this PWAShell.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('FCM-token-handle', { detail: token }))") and catch this on web side.

Could you please provide a tutorial on how to do this? I need only the device id.

I did it in this way. May be it will helps you.

PushNotifications.swift

func returnPermissionResult(isGranted: Bool){
    DispatchQueue.main.async(execute: {
        if (isGranted){
            Messaging.messaging().token { token, error in
                if let error = error {
                    print("Error fetching FCM registration token: \(error)")
                } else if let token = token {
                    print("FCM registration token: \(token)")

                    eDrive.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('push-permission-request', { detail: { state: 'granted',  token: '\(token)' }}))")
                }
            }
        }
        else {
            eDrive.webView.evaluateJavaScript("this.dispatchEvent(new CustomEvent('push-permission-request', { detail: { state: 'denied' }}))")
        }
    })

}
fenbru commented 1 year ago

Hey @khmyznikov and @igor-shyrnin , how can we hook up that user token to subscribe to all messages, not just topic ones?

Thx in advance!

fenbru commented 1 year ago

Hey @khmyznikov and @igor-shyrnin , how can we hook up that user token to subscribe to all messages, not just topic ones?

Thx in advance!

Any idea about this guys?