GithubHelp home page GithubHelp logo

capacitor-community / fcm Goto Github PK

View Code? Open in Web Editor NEW
235.0 18.0 81.0 13.83 MB

Enable Firebase Cloud Messaging for Capacitor apps

Home Page: https://capacitor.ionicframework.com/docs/

License: MIT License

Ruby 4.21% Java 15.71% Objective-C 2.63% Swift 27.93% JavaScript 5.16% TypeScript 33.69% HTML 2.83% SCSS 7.84%
capacitor ios android fcm firebase ionic angular

fcm's Introduction


Capacitor FCM

@capacitor-community/fcm

Capacitor community plugin for enabling FCM capabilities


Sponsors

Chatness AI

Maintainers

Maintainer GitHub Social
Stewan Silva stewones @stewones

Notice 🚀

We're starting fresh under an official org. If you were using the previous npm package capacitor-fcm, please update your package.json to @capacitor-community/fcm. Check out changelog for more info.

Installation

Using npm:

npm install @capacitor-community/fcm

Using yarn:

yarn add @capacitor-community/fcm

Sync native files:

npx cap sync

Notice

This plugin is intended to be used combined with Capacitor API for Push Notifications. Capacitor only provides APN token whereas this plugin offers the possibility to work with FCM tokens and more.

API

method info platform
subscribeTo subscribe to fcm topic ios/android
unsubscribeFrom unsubscribe from fcm topic ios/android
getToken get fcm token to eventually use from a server ios/android
refreshToken refresh fcm token to get a new one ios/android
deleteInstance remove local fcm instance completely ios/android
setAutoInit enable the auto initialization of the library ios/android
isAutoInitEnabled check whether auto initialization is enabled ios/android

Usage

import { FCM } from '@capacitor-community/fcm';
import { PushNotifications } from '@capacitor/push-notifications';

// external required step
// register for push
await PushNotifications.requestPermissions();
await PushNotifications.register();

// now you can subscribe to a specific topic
FCM.subscribeTo({ topic: 'test' })
  .then(r => alert(`subscribed to topic`))
  .catch(err => console.log(err));

// Unsubscribe from a specific topic
FCM.unsubscribeFrom({ topic: 'test' })
  .then(() => alert(`unsubscribed from topic`))
  .catch(err => console.log(err));

// Get FCM token instead of the APN one returned by Capacitor
FCM.getToken()
  .then(r => alert(`Token ${r.token}`))
  .catch(err => console.log(err));

// Delete the old FCM token and get a new one
FCM.refreshToken()
  .then(r => alert(`Token ${r.token}`))
  .catch(err => console.log(err));

// Remove FCM instance
FCM.deleteInstance()
  .then(() => alert(`Token deleted`))
  .catch(err => console.log(err));

// Enable the auto initialization of the library
FCM.setAutoInit({ enabled: true }).then(() => alert(`Auto init enabled`));

// Check the auto initialization status
FCM.isAutoInitEnabled().then(r => {
  console.log('Auto init is ' + (r.enabled ? 'enabled' : 'disabled'));
});

Add Google config files

Navigate to the project settings page for your app on Firebase.

iOS

Download the GoogleService-Info.plist file. In Xcode right-click on the yellow folder named "App" and select the Add files to "App".

Tip: if you drag and drop your file to this location, Xcode may not be able to find it.

Android

Download the google-services.json file and copy it to android/app/ directory of your capacitor project.

Certificate

iOS setup

  • Install homebrew (once)
  • brew install cocoapods (once a time)
  • ionic start my-cap-app --capacitor
  • cd my-cap-app
  • mkdir www && touch www/index.html
  • npx cap add ios
  • npm install --save @capacitor-community/fcm
  • npx cap sync ios (always do sync after a plugin install)
  • npx cap open ios
  • sign your app at xcode (general tab)
  • enable remote notification capabilities
  • add GoogleService-Info.plist to the app folder in xcode
// (optional) turn off `swizzling` in the `info.plist`
<key>FirebaseAppDelegateProxyEnabled</key>
<string>NO</string>

Tip: every time you change a native code you may need to clean up the cache (Product > Clean build folder) and then run the app again.

Prevent auto initialization

If you need to implement opt-in behavior, you can disable the auto initialization of the library by following the Firebase docs.

Android setup

  • ionic start my-cap-app --capacitor
  • cd my-cap-app
  • mkdir www && touch www/index.html
  • npx cap add android
  • npm install --save @capacitor-community/fcm
  • npx cap sync android (always do sync after a plugin install)
  • npx cap open android
  • add google-services.json to your android/app folder

Now you should be set to go. Try to run your client using ionic cap run android --livereload.

Tip: every time you change a native code you may need to clean up the cache (Build > Clean Project | Build > Rebuild Project) and then run the app again.

Variables

This plugin will use the following project variables (defined in your app's variables.gradle file):

  • $firebaseMessagingVersion version of com.google.firebase:firebase-messaging (default: 23.1.2)

Prevent auto initialization

If you need to implement opt-in behavior, you can disable the auto initialization of the library by following the Firebase docs.

Example

License

MIT

Contributors ✨

Thanks goes to these wonderful people (emoji key):

stewones
stewones

💻 📖
Daniel Pereira
Daniel Pereira

💻 📖
Priyank Patel
Priyank Patel

💻
Nikolas
Nikolas

🚧
Ben Schattinger
Ben Schattinger

💻
James Manners
James Manners

💻
Borja Rodríguez
Borja Rodríguez

🚧
Karrlllis
Karrlllis

📖
jamesmah
jamesmah

💻
Josh Sharpe
Josh Sharpe

🚧
Mantas Šimkūnas
Mantas Šimkūnas

💻 📖
Olivier Overstraete
Olivier Overstraete

🚧
Hemang Kumar
Hemang Kumar

💻 🚧
Luca Ban
Luca Ban

📖
Alex Griffith
Alex Griffith

💻 🚧
bdirito
bdirito

🚧
Ryan
Ryan

🚧
Josué Moreno
Josué Moreno

💻
Marc
Marc

🚧
Florian Gyger
Florian Gyger

💻
jcesarmobile
jcesarmobile

💬 📖 🚧
Rami Khafagi
Rami Khafagi

💻
Bittor Poza
Bittor Poza

💻
Vishal Isharani
Vishal Isharani

🚧
Shunta KARASAWA
Shunta KARASAWA

🚧

This project follows the all-contributors specification. Contributions of any kind welcome!

fcm's People

Contributors

bdirito avatar bipoza avatar borodiliz avatar danielprrazevedo avatar halomakes avatar hemangsk avatar iolivier avatar jcesarmobile avatar jmannau avatar josh-m-sharpe avatar josuelmm avatar karrlllis avatar kashz avatar lights0123 avatar marcjulian avatar mesqueeb avatar mineminemine avatar msimkunas avatar nicofrand avatar nikoskip avatar priyankpat avatar ramikhafagi96 avatar stewones avatar vishal-isharani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fcm's Issues

Data only (Silent) notifications on iOS

I can get push notifications on both iOS and Android,
But data only (silent) notifications are only delivered to Android.
Can you show what need to be in the push json or app configuration in order to receive these data only notifications on iOS?

project exhibits a woeful lack of release management and testing

Exhibits:
#43
#44

I just spend 45 minutes "fixing" the issues in #43 only to realize #44 existed (and has been closed, but the OP there seems to think it's still broken an additional configuration needs to happen.)

Should I bother with 1.0.6 or should I wait for 1.0.7?

What steps are being taken to ensure that releases for this repo are actually production ready?

Getting "class file for androidx.appcompat.app.AppCompatActivity not found" while building

I'm getting an error while building the app in Android Studio:

.../node_modules/capacitor-fcm/android/capacitor-fcm/src/main/java/io/stewan/capacitor/fcm/FCMPlugin.java:96: error: cannot access AppCompatActivity
        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(getActivity(),  new OnSuccessListener<InstanceIdResult>() {
                                                                                         ^
  class file for androidx.appcompat.app.AppCompatActivity not found

I'm using @capacitor/core v 2.0.0 and @capacitor/android v 2.0.0

Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.

Hi There,

Great plugin. I've built a series of apps and happily integrated this plugin. However today I'm struggling to get iOS to work. I've followed all of the steps and now when running the application on an iPhone Xcode gives me the following error:

The object <FCM: 0x2810fec00> does not respond to -messaging:didReceiveRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.

Build Error

Hi,

I got build error like below,

No podspec found for CapacitorFcmin../../node_modules/capacitor-fcm`

I have installed capacitor-fcm using npm and run npx cap update ios. I got the above error

Capacitor Info

`capacitor-fcm: 0.0.7

@capacitor/cli: 1.1.1

@capacitor/core: 1.1.1

@capacitor/android: 1.1.1

@capacitor/ios: 1.1.1

`

Conflicting with Capacitor Push notification

Hello

with the new Capacitor Push notification that supports FCM on iOS (which can not be disabled for some reason!), I found 2 issues when you implement capacitor-fcm

  • Token returned by "registration" event will be Apple Token, not FCM token
  • When you push a message from FCM console you will get 2 notifications in the App! (If you implement "pushNotificationReceived")

Any way to fix this?

PS: the current Capacitor Push notification implementation does not return FCM token, only apple token

[Android] Package io.stewan.capacitor.fcm.FCMPlugin does not exist

Hi,

I'm trying to use this plugin but I'm having trouble when I try to build on Android. I follow the README guide step by step but it seems that the Java package is not being included. These are the commands I'm running before building on Android Studio:

npm run build
npx cap copy 
npx cap open android

Any ideas?

Thanks!

Capacitor update now FCM to iOS no longer working - old capacitor-fcm package

I updated capacitor to the latest version (2.4.6) from 1.1.1 for @capacitor/ios only. I left the rest at 1.1.1.
In order to resolve some swift compiler errors in the latest Xcode.

I have released the app to the store and FCM to iOS devices does not seem to be working.
It says in the FCM dashboard that 22 have been sent to iOS (should be around 1000) and none of my iOS devices have received them. It still works fine for Android.

I am using the package capacitor-fcm v0.0.7.

I know this has now been replaced with @capacitor-community/fcm as I have used that in another project. https://www.npmjs.com/package/@capacitor-community/fcm

Do I have to downgrade Capacitor or upgrade to the new fcm package or should capacitor-fcm still work with capacitor 2.4.6?

Sample code

Sharing my code as an example for anyone interested to use this plugin (please install the plugin and follow the instruction in the README file before using below code).

app.component.ts

initializeApp() {
    this.platform.ready().then(() => {
        if (Capacitor.isPluginAvailable('SplashScreen')) {
            Plugins.SplashScreen.hide();
        }
        if (Capacitor.isPluginAvailable('PushNotifications')) {
                PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
                    alert('pushNotificationReceived ' + notification.body);
                    console.log('pushNotificationReceived ', notification.body);
                });
                PushNotifications.addListener('pushNotificationActionPerformed', (notification: PushNotificationActionPerformed) => {
                    alert('pushNotificationActionPerformed ' + JSON.stringify(notification));
                    console.log('notification ', JSON.stringify(notification));
                });
                PushNotifications.addListener('registrationError', (error: any) => {
                    alert('error on register ' + JSON.stringify(error));
                    console.log('error on register ',  JSON.stringify(error));
                });
        }
    });
  }

dashboard.page.ts

ngOnInit() {
        if (Capacitor.isPluginAvailable('PushNotifications')) {
        PushNotifications.register();
        PushNotifications.addListener('registration', (token: PushNotificationToken) => {
            console.log('FCM ',token.value);
        });
      }
}

2.0.0 release notes?

Just updating my deps and upgraded to 2.0.0 for this plugin. Since a major bump indicates breaking changes, is there a changelog anywhere I can read?

Remote notifications are not supported in the simulator

Hi!

Just want to ask something. I'm getting this error:

[Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: remote notifications are not supported in the simulator

when trying to run

PushNotifications.addListener('registration', (data) => {
      console.log('REGISTRATION', data);
 });

Here's my xcode and device infos:

Xcode: Version 11.3.1 (11C504)
Iphone 11 Pro Max with IOS 13.3

Any help would be much appreciated.

Communication between two different apps

Hi,

I'm building 2 ionic apps that have to send notifications to each other.
I created 2 different apps under the same Firebase Project (actually 4, iOS & Android), This in turn means I have 2 GoogleService-Info.plist files with the different PRODUCT_BUNDLE_IDENTIFIER names.

My problem is that only one of these PRODUCT_BUNDLE_IDENTIFIER and GoogleService-Info.plist combinations works. It looks like sending notifications between these two is impossible even tho they share the same Firebase Project and Cloud FireStore Database.

Is notification communication between two different apps with different GoogleService-Info.plist files possible?

Firebase InstanceID has been removed - iOS builds failing

Describe the bug
We are using fastlane to build iOS apps. Since 11th of May 2021 our builds are failing with error message:

`@capacitor-community/fcm/ios/Plugin/Plugin/Plugin.swift:7:8: �[31mno such module 'FirebaseInstanceID'

import FirebaseInstanceID`

The Firebase iOS SDK (v8.0.0) is now available and Firebase InstanceID has been removed.

There is a migration guide on how to move from Instance ID to Firebase Installations.

Expected behavior
After migration there should be no issues with this plugin.

iOS build error "extra argument 'toTopic' in call"

When using capacitor-fcm in my project Xcode shows me the
following error when building the application: "extra argument 'toTopic' in
call";

this occurs in the following function:
@objc func subscribeTo(_ call: CAPPluginCall) { let topicName = call.getString("topic") ?? "" Messaging.messaging().subscribe(toTopic: topicName) { error in // print("Subscribed to weather topic") if ((error) != nil) { print("ERROR while trying to subscribe topic \(topicName)") call.error("Can't subscribe to topic \(topicName)") }else{ call.success([ "message": "subscribed to topic \(topicName)" ]) } } }

(the same error is received at the unsubscribe call).

the last issue here is the getToken() function:

InstanceID.instanceID().instanceID { (result, error) in provides the error: 'Static member 'instanceID' cannot be used on instance of type 'InstanceID'"

Fail to subscribe to topic

I try to subscribe to an X token in Android and I can't make it happen and the catch doesn't give me any results

I have the latest version 1.0.8 installed, synchronize the project, recreate it, add part of my implementation.

PushNotifications.register()
.then(() => {
fcm
.subscribeTo({ topic: topicName })
.then(r => console.log('Suscrito a topic', topicName))
.catch(err => console.log('Error', err));
})
.catch((err) => {
console.log('Topic ' + topicName + '!');
console.log('Error catch subscribe to topic', JSON.stringify(err));
}
);

the anwser of Android Studio "error catch" JSON.stringify(err) shown
" typeerror cannot read property 'toSubscribe' of undefined "

I try with the example code(https://github.com/capacitor-community/fcm/blob/master/example/src/app/home/home.page.ts) a shows the same error

error

Unable to receive notifications on iOS even with demo app

Currently trying to get this to work on iOS.

  1. Added iOS App to Firebase
  2. Generated and .p8 file and added to Firebase
  3. Generated certificate for APNs Development for my app aswell as a povisioning profile for development
  4. Added GoogleService-Info.plist to App
  5. Build app on iPad, receive token or subscribe to topic

But I am not able to receive notifications with token or via the topic... on Android everything works fine though :/

Any ideas what I am missing?

[Android] Package io.stewan.capacitor.fcm.FCMPlugin does not exist

I started a new issue with the same title I found an existing issue ;)
But steps mentioned did not help. I also tried ./gradlew --refresh-dependencies and amending capacitor.settings.gradle as in #43 - but did not help.

Any ideas, what I could do to force copying plugin files and install all needed dependencies?

image

To Reproduce
Steps according to Android Setup: https://github.com/capacitor-community/fcm
Using gradle 6.1

Expected behavior
Should find import of io.stewan.capacitor.fcm.FCMPlugin.
I also tried to copy java files manually to the src/ folder, but then Firebase Classes can't be found.

Screenshots
Where should the java package be placed?
image

Additional context
Gradle 6.1
Andriod Studio 4.0

cannot build android after migration from [email protected]

Android production builds are failing with the following now that we've migrated to this version of the plugin.

* What went wrong:
Could not determine the dependencies of task ':app:collectReleaseDependencies'.
> Could not resolve all task dependencies for configuration ':app:releaseRuntimeClasspath'.
   > Could not resolve project :capacitor-community-fcm.
     Required by:
         project :app
      > Unable to find a matching configuration of project :capacitor-community-fcm:
          - None of the consumable configurations have attributes.

No virtual method subscribeToTopic

Describe the bug
After installing the plugin (following the instructions) and building it successfully I get an error during runtime on Android 10. Is this caused by a plugin conflict or a version mismatch? Perhaps something is missing from the installation instructions? I couldn't find an obvious plugin conflict or version mismatch.

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version 20.04

Smartphone (please complete the following information):

  • Device: Galaxy A40
  • OS: Android 10

Additional context

E/Capacitor: Serious error executing plugin
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:99)
at com.getcapacitor.Bridge$1.run(Bridge.java:521)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.os.HandlerThread.run(HandlerThread.java:67)
Caused by: java.lang.NoSuchMethodError: No virtual method subscribeToTopic(Ljava/lang/String;)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/messaging/FirebaseMessaging; or its super classes (declaration of 'com.google.firebase.messaging.FirebaseMessaging' appears in /data/app/app.apk)
at com.getcapacitor.community.fcm.FCMPlugin.subscribeTo(FCMPlugin.java:28)
at java.lang.reflect.Method.invoke(Native Method) 
at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:99) 
at com.getcapacitor.Bridge$1.run(Bridge.java:521) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:237) 
at android.os.HandlerThread.run(HandlerThread.java:67) 

Need Explanations

Hi,

Would you kindly explain the usage of each methods?

  1. What is the purpose of subscirbeTo method?
  2. What is the purpose of unsubcribeFrom method?
  3. Is the getToken method return new Fcm token each time?

Kindly explain

Support web platform

I noticed this plugin does not support web/PWA. FCM users can just use the Firebase client for JS, but for a better cross-platform experience, we can wrap the client in the existing API of this plugin.

@CFT-Chris Maybe you could chime in? I saw your plugin seems to provide the necessary functionality. Perhaps they could be merged?

ref: ionic-team/capacitor#1892 (comment)

Multiple SenderIDs/FCM projects?

Is your feature request related to a problem? Please describe.
Maybe? I have an app that I don't want to ship credentials with. Instead, I want the app to contact a server to discover the FCM details for SenderID etc. My app can connect to a self hosted server setup, so I want to support self hosted users using FCM. I think this is possible today using native FCM and calling getToken after GETing a senderID.

Describe the solution you'd like
I'd like to have my app be able to initialize FCM's config (senderID specifically) in JS on iOS and Android. I currently do this today for the PWA. Ideally I wouldn't have to provide the FCM credentials as a plist or JSON file, but I'm fine doing that if I can overwrite those values in JS.

Describe alternatives you've considered
I think it's fine if I can't do this, but it would be really cool if it works!!

Additional context

Android Build failed. unexpected char in _modules/capacitor-fcm/android\capacitor

Hey.
I have a problem emulating my app with Android Studio.
The Project fails in the startup
I've done all the steps from the ReadMe.
It always shows this error:
Unbenannt

Versions I use:
"@capacitor/android": "^1.1.0",
"@capacitor/cli": "1.0.0-beta.22",
"@capacitor/core": "1.0.0-beta.22",
"@capacitor/ios": "^1.0.0",
"capacitor-fcm": "0.0.6",

I've also done the extra step but it does'n even recognize io.stewan.capacitor.fcm.FCMPlugin
Unbenannt

Do you have any idea what the problem could be?

How to handle refreshToken?

How to handle the refreshToken events?

In the capacitor Push Notification plugin is implemente the onNewToken() method.
But no listener is availble, only the registered one.
Is the event fire in the register listener, if not, how to handle the refreshToken problem?

best regards.

Usage with @capacitor-community/firebase-analytics causes crash on android

Describe the bug
Hi! Im using this plugin together with @capacitor-community/firebase-analytics (both on latest version) and when I run my app on my android device it crashes on startup.

To Reproduce
Steps to reproduce the behavior:

  1. Install both @capacitor-community/fcm and @capacitor-community/firebase-analytics.
  2. Run npx cap sync

In my MainActivity.java file, I have added

import com.getcapacitor.community.fcm.FCMPlugin;
import com.getcapacitor.community.firebaseanalytics.FirebaseAnalytics;

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
        add(FirebaseAnalytics.class);
        add(FCMPlugin.class);
    }});
  }
}

When I run the app through android studio, it builds successfully but crashes instantly after splashscreen.

Smartphone (please complete the following information):

  • Device: OnePlus 8 Pro
  • OS: MacOS 10.14.6
  • Android Studio: 3.6.2
  • @capacitor/android: 2.4.0,
  • @capacitor/core: 2.4.0,
  • @capacitor-community/fcm: 1.0.8,
  • @capacitor-community/firebase-analytics: 0.2.0,

Additional context

I have tried reversing the order of the added plugins but to no luck.

On iOS everything works perfectly.

If I comment out the FCMPlugin.class line the app starts.
If I remove the analytics line + import, the app still crashes. I have to remove the plugin completely for the app to work again.

So I can start the app using either of these plugins seperately but not together.

Not receiving any Push notification

Describe the bug
I'm not receiving any push notification from console. I got the correct token the one for FCM not the APNS.

To Reproduce
Steps to reproduce the behavior:
I followed the steps, checked the demo also

Expected behavior
Should be able to receive a notif even a log on the console

Screenshots
If applicable, add screenshots to help explain your problem.

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6] iPhone 12 pro
  • OS: [e.g. iOS8.1] iOS 14
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Ionic:

Ionic CLI : 6.12.3 (/Users/jongbanaag/.config/yarn/global/node_modules/@ionic/cli)
Ionic Framework : @ionic/react 5.1.0

Capacitor:

Capacitor CLI : 2.4.2
@capacitor/core : 2.4.2

Utility:

cordova-res : not installed
native-run : not installed

System:

NodeJS : v14.15.1 (/Users/jongbanaag/.nvm/versions/node/v14.15.1/bin/node)
npm : 6.14.8
OS : macOS Big Sur

iOS notifications not working on iOS 14.4

Describe the bug
Whenever I do exactly what has been mentioned in the documentation, I am unable to get notifications to show up on my iOS device.

This does work for android.

When I look at the logs I get these messages at the start of the app:

2021-03-17 17:08:05.664704+0100 App[514:45703] 6.24.0 - [Firebase/Core][I-COR000003] The default Firebase app has not yet been configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your application initialization. Read more: https://goo.gl/ctyzm8.

2021-03-17 17:08:05.773091+0100 App[514:45709] 6.24.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging
to ensure proper integration.

2021-03-17 17:08:05.787817+0100 App[514:45709] 6.24.0 - [Firebase/Messaging][I-FCM002023] The object <FCM: 0x280e42700> does not respond to -messaging:didReceiveRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.
Loading network plugin

Then when I do the following:

import { FCM } from '@capacitor-community/fcm';
import { Plugins, PushNotification, PushNotificationToken, PushNotificationActionPerformed, NotificationChannel } from '@capacitor/core';

const { PushNotifications, LocalNotifications } = Plugins;
const fcm = new FCM();

@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  constructor() { }

  initNotifications() {
    PushNotifications.requestPermission().then( result => {
      if (result.granted) {
        PushNotifications.register().then((value) => {
          PushNotifications.addListener('registration',
          async (token: PushNotificationToken) => {
            console.log("Registration token APNS:", token);
            fcm
              .getToken()
              .then((fcmvalue) => {
                console.log("Registration token FCM:", fcmvalue.token);
              })
              .catch((error) => {
                console.error(error);
              });
            const data = await Promise.all([fcm.subscribeTo({ topic: 'news'}), fcm.subscribeTo({ topic: 'events'}), fcm.subscribeTo({ topic: 'test-channel'})]);
           });
        });
    }});
  }
}

I get the following logs:

⚡️  TO JS {"granted":true}
⚡️  To Native ->  PushNotifications register 67907362
⚡️  To Native ->  PushNotifications addListener 67907365
⚡️  TO JS {"value":"XXXXXXXXXXXXX"} <- same as below
⚡️  [log] - Registration token APNS: {"value":"XXXXXXXXXXXXX"}
⚡️  To Native ->  FCMPlugin getToken 67907369
⚡️  To Native ->  FCMPlugin subscribeTo 67907371
⚡️  To Native ->  FCMPlugin subscribeTo 67907372
⚡️  To Native ->  FCMPlugin subscribeTo 67907373
⚡️  TO JS {"token":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"} <- same as below but not as above
⚡️  [log] - Registration token FCM: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
⚡️  TO JS {"message":"subscribed to topic news"}
⚡️  TO JS {"message":"subscribed to topic test-channel"}
⚡️  TO JS {"message":"subscribed to topic events"}

Now when I send a message to either the FCM token as a test message directly from FCM, or to the test-channel topic.
There is no notification shown on iOS.

When I send this to the test-channel topic it does show up on android but not on iOS.

I am using the following versions of software:

"@capacitor-community/fcm": "^1.1.0",
"@capacitor/android": "^2.4.0",
"@capacitor/core": "^2.4.0",
"@capacitor/ios": "^2.4.0",
"@ionic/angular": "^5.5.5"

with the following ionic info:

❯ ionic info

Ionic:

   Ionic CLI                     : 6.12.3 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.5.5
   @angular-devkit/build-angular : 0.1102.3
   @angular-devkit/schematics    : 11.2.3
   @angular/cli                  : 11.2.2
   @ionic/angular-toolkit        : 2.3.3

Capacitor:

   Capacitor CLI   : 1.5.3
   @capacitor/core : 2.4.7

Cordova:

   Cordova CLI       : 9.0.0 ([email protected])
   Cordova Platforms : none
   Cordova Plugins   : no whitelisted plugins (0 plugins total)

Utility:

   cordova-res (update available: 0.15.3) : 0.14.1
   native-run (update available: 1.3.0)   : 0.2.8

System:

   ios-deploy : 1.9.4
   NodeJS     : v15.7.0 (/usr/local/Cellar/node/15.7.0/bin/node)
   npm        : 7.4.3
   OS         : macOS Big Sur
   Xcode      : Xcode 12.4 Build version 12D4e

I have notifications enabled on iOS and allowed for the specific app that I'm using.

I'm using version 14.4 of iOS

To Reproduce
Steps to reproduce the behavior:

  1. create an app using ionic
  2. follow the instructions on firebase to setup an app for fcm and follow the documentation on this community plugin's readme.
  3. Use the correct code and test it on an actual device by sending messages from fcm.

Expected behavior
I expect iOS to receive the notification from fcm.

Smartphone:

  • Device: iPhone SE
  • OS: iOS 14.4
  • Browser: mobile-safari

Additional context
I don't know whether it's normal to get these first messages on startup, I've looked at the code of the capacitor-community/fcm plugin and it clearly calls Firebase.configure and all the other stuff. Yet, it is complaining about this on startup. Could it be that there is some kind of conflict somewhere? Or is this normal behaviour?

That seems to be the only thing I could think of that would make this not work.
Otherwise everything seems fine (console logs show the correct information)

I'm thinking about re-adding the platform with ionic capacitor add ios...
But this requires me to check if all the native configs of all of my native functionality still works.

We used to use capacitor-fcm from npm (the deprecated version), which has worked in previous versions of the app.
But because we've upgraded from ionic 4 to 5 and upgraded angular from 7 to 11, we needed to also upgrade this deprecated plugin to the capacitor-community/fcm plugin. Which is now giving us these issues.

Note:
I've already cleaned the build folder and did a npx cap sync and npx cap copy ios... This is defined in my build script by default so shouldn't give me issues.

Ionic Capacitor-FCM - Error to subscribe/unsubscribe topic in iOS

I followed all the steps from tutorial and in android is working fine, but in iOS is showing only this error when I try subscribe or unsubscribe a topic:

{"line":172816,"column":25,"sourceURL":"capacitor://localhost/vendor-es2015.js"}

My infos:

Ionic:

Ionic CLI : 5.4.16
Ionic Framework : @ionic/angular 4.11.10
@angular-devkit/build-angular : 0.900.6
@angular-devkit/schematics : 9.0.6
@angular/cli : 9.0.6
@ionic/angular-toolkit : 2.0.0

Capacitor:

Capacitor CLI : 2.0.0
@capacitor/core : 2.0.0

Cordova:

Cordova CLI : 9.0.0 ([email protected])
Cordova Platforms : none
Cordova Plugins : no whitelisted plugins (0 plugins total)

Utility:

cordova-res (update available: 0.11.0) : 0.10.0
native-run : not installed

System:

NodeJS : v12.16.1 (/usr/local/bin/node)
npm : 6.13.4
OS : macOS Catalina
Xcode : Xcode 11.4 Build version 11E146

Fcm topics don't handling push notification when app was killed

I have a problem with the subscription via topics. Using capacitor's Push Notification plugin with the fcm plugin I can't receive notifications when the app is closed. If I send a direct notification to the token generated by the Push Notification plugin, the notification also arrives at closed application. After the first direct submission, the application also begins to receive notifications via topics that are closed until a new token is generated.

iOS Build Error In subscribeTo and unsubscribeFrom

Hello,

This may be something simple I am missing but have not been able to figure out it yet.

I have successfully used this plugin for android. Now going through the setup process for iOS I am running into the following build error.

"Type of expression is ambiguous without more context" in subscribeTo/unsubscribeFrom. See attached image.

Any help in figuring this out and pointing me in a direction would be appreciate.
5c928e1f6b9579b5ed73aa20ddbc1e88

iOS FCM getToken

How can we combine PushNotifications.addListener( 'registration') with this plugin to receive an FCM token on iOS?

I have tried this (but the promise does not fire, so we never get the "fcm_token" below):


PushNotifications.addListener("registration", (token) => {
    fcm.getToken().then(fcm_token => console.log("FCM Token:", JSON.stringify(fcm_token))); 
});

In the xcode log all we see is that we receive APNS token and then:
...
To Native -> FCMPlugin getToken 655837

Any ideas?

Capacitor 3 Support

Capacitor 3 is currently in alpha. It would be great if this plugin released a Capacitor 3 compatible version around the same time as the full release.

The official Capacitor Push Notifications Plugin was just updated to be v3 compatible. Once a new version is pushed to npm, we'd be able to start the work on migrating over.

Happy to help out if I can 😄

Import in AndroidManifest

Following the setup process for android, when I add the import, it cant found the community path:

import com.getcapacitor.community.fcm.FCMPlugin;

the community word is in red

The app looks like it works fine, also the plugin

any ideas? thanks

FCM, FCMPlugin are always undefined

FCM, FCMPlugin are always undefined
Our Ionic setup with Capacitor using capacitor-community/fcm to listen for push notifications for defined topics (currently only all) does not work as expected. Calling fcm.subscribeTo() as well as FCMPlugin.subscribeTo() result in an error when running in an Android device:

Cannot read property 'subscribeTo' of undefined

My first thoughts were, that this is an Angular / Ionic specific issue, but after trying a couple of different solutions, I concluded, that there is another problem in our setup:

  • using the FCM class via Angulat Provider did not work
  • creating an fcm variable with const fcm = new FCM() did not work
  • using FCMPlugin.subscribeTo() directly did not work
  • wrapping the function call in an additional this.application.ready().then() callback did not work too

To Reproduce

  1. Setup the tabs ionic project with capacitor support
  2. Add the Push Notifications features as defined below

Package and software versions

// packages.json
"@capacitor-community/fcm": "^1.0.8",
"@capacitor/android": "^2.4.4",
"@capacitor/core": "2.4.4",

// cli
ionic --version
6.12.3

npm --version
6.14.5

npx cap --version
2.4.4

Notes

  • the build works like charm, the problem seems to occur at runtime
  • Sending messages directly via Firebase console works fine, but in contrast to our custom messaging serverside applicatin it does not send to a specific topic

Code sample

import { Component, OnInit } from '@angular/core';

import {
  Plugins,
  PushNotification,
  PushNotificationToken,
  PushNotificationActionPerformed,
} from '@capacitor/core';

const { PushNotifications } = Plugins;
import { Platform } from '@ionic/angular';
import { FCM } from '@capacitor-community/fcm';
const fcm = new FCM();

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements OnInit {

  constructor(private platform: Platform) {

  }

  ngOnInit() {
    // On success, we should be able to receive notifications
    PushNotifications.addListener('registration',
      (token: PushNotificationToken) => {
        alert('Push registration success, token: ' + token.value);

        alert("Trying to subscribe to topic 'all'...");

       // the error is thrown here: fcm.subscribeTo() is not available, fcm is undefined

        fcm.subscribeTo({ topic: 'all' })
          .then((r) => alert("subscribed to topic 'all'. Should receive notifications to this topic from now on."))
          .catch((err) => console.log('Error on PushNotifications.fcm.subscribeTo():' + JSON.stringify(err)));
      }
    );

    // Some issue with our setup and push will not work
    PushNotifications.addListener('registrationError',
      (error: any) => {
        alert('Error on registration: ' + JSON.stringify(error));
      }
    );

    // Show us the notification payload if the app is open on our device
    PushNotifications.addListener('pushNotificationReceived',
      (notification: PushNotification) => {
        alert('Push received: ' + JSON.stringify(notification));
      }
    );

    // Method called when tapping on a notification
    PushNotifications.addListener('pushNotificationActionPerformed',
      (notification: PushNotificationActionPerformed) => {
        alert('Push action performed: ' + JSON.stringify(notification));
      }
    );

    // Request permission to use push notifications
    // iOS will prompt user and return if they granted permission or not
    // Android will just grant without prompting
    PushNotifications.requestPermission().then( result => {
      if (result.granted) {
        // Register with Apple / Google to receive push via APNS/FCM
        PushNotifications.register().then((_) => {
          console.log("Registration success (callback).");
        })
        .catch((err) => alert('Error on PushNotifications.register():' + JSON.stringify(err)));;
      } else {
        // Show some error
      }
    });
  }
}

Notification receive different behavior

Hi,

I switched my application FCM to this package from an old one.
The case:

  • I would like to navigate my user inside my application pages, when the push notification is tapped. For example if the user get a new notification about a new task, when the user click on the notification the app will navigate the user to the task details page.

I would like to explain some behavior difference between this FCM package and the old Cordova FCM package (cordova-plugin-fcm-with-dependecy-updated):
Some lines from Cordova package readme:

Application is in foreground:

The notification data is received in the JavaScript callback without notification bar message (this is the normal behavior of mobile push notifications).
For Android, to show the notification received on the foreground, it's recommended to use cordova-plugin-local-notification as it provides many presentation and interaction features.
Application is in background or closed:

The device displays the notification message in the device notification bar.
If the user taps the notification, the application comes to foreground and the notification data is received in the JavaScript callback.
If the user does not tap the notification but opens the application, nothing happens until the notification is tapped.

The important parts in the foreground behavior, when the app get a new notification while it is in foreground: it does nothing. In the Capacitor-C FCM package, the subscription run the code in foreground too, immediately without click on the push notification.
The difference in the background case also similar "If the user does not tap the notification but opens the application, nothing happens until the notification is tapped.", so if the user get notification, but doesn't tap on it, in my case the app should not be redirect to a different page.

Feature request:
It would be nice if the payload get a new parameter like the "coldstart" and "foreground" parameters, for example "tapped", this will be a boolean, and it will be true, if the notification is tapped and will be false when the subscription handler called automatically by FCM.

Swift compiler error with "Extra trailling closure" on Plugin.swift file

Describe the bug
I have installed the fcm plugin and tried to build on iOS.
When i build the iOS project after have all installed and sync i have this error on iOS project.

In Plugin.swift file on line 36, 51, 63.

Extra trailling closure passed in call

And on line 86 , 92,

Messaging has no member 'isAutoInitEnabled'

Screenshots
If applicable, add screenshots to help explain your problem.

ionic info

Ionic:

Ionic CLI : 6.13.1
Ionic Framework : @ionic/angular 5.6.2
@angular-devkit/build-angular : 0.1102.5
@angular-devkit/schematics : 11.2.5
@angular/cli : 11.2.5
@ionic/angular-toolkit : 3.1.1

Capacitor:

Capacitor CLI : 2.4.7
@capacitor/core : 2.4.7

Utility:

cordova-res : not installed
native-run (update available: 1.3.0) : 0.2.8

System:

NodeJS : v12.19.0 (/Users/johanpujol/.nvm/versions/node/v12.19.0/bin/node)
npm : 6.14.8
OS : macOS Big Sur
ios : 11.0
Swift compile : 5.0

Screenshot 2021-03-24 at 11 02 14

Crashes on getToken()

Hi,

I've been using this plugin for some time and recently upgraded another capacitor plugin and synced my packages. Not sure what would cause this to happen because nothing changed with this package (no new version in yarn.lock), but I am now getting this error after my app's splash screen.

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.getcapacitor.Bridge$1.run(Bridge.java:551)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:99)
        at com.getcapacitor.Bridge$1.run(Bridge.java:542)
        at android.os.Handler.handleCallback(Handler.java:938) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.os.HandlerThread.run(HandlerThread.java:67) 
     Caused by: java.lang.IllegalStateException: Method addObserver must be called on the main thread
        at androidx.lifecycle.LifecycleRegistry.enforceMainThreadIfNeeded(LifecycleRegistry.java:317)
        at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:172)
        at androidx.fragment.app.Fragment.initLifecycle(Fragment.java:471)
        at androidx.fragment.app.Fragment.<init>(Fragment.java:451)
        at com.google.android.gms.common.api.internal.zzc.<init>(Unknown Source:1)
        at com.google.android.gms.common.api.internal.zzc.zza(Unknown Source:14)
        at com.google.android.gms.common.api.internal.LifecycleCallback.getFragment(Unknown Source:3)
        at com.google.android.gms.common.api.internal.LifecycleCallback.getFragment(Unknown Source:7)
        at com.google.android.gms.tasks.zzu$zza.zza(Unknown Source:1)
        at com.google.android.gms.tasks.zzu.addOnSuccessListener(Unknown Source:36)
        at com.getcapacitor.community.fcm.FCMPlugin.getToken(FCMPlugin.java:82)

I was able to fix it by changing the getToken method to:

getActivity().runOnUiThread(() -> {
            FirebaseMessaging.getInstance().getToken().addOnSuccessListener(getActivity(), token -> {
                JSObject data = new JSObject();
                data.put("token", token);
                call.success(data);
            }).addOnFailureListener(e -> call.error("Failed to get instance FirebaseID", e));
        });

But I'm not an Android developer so I'm not sure if that is all a good idea.

Android app crashes after splash screen

When running on device from Android Studio the app crashes right after the splash screen and I get the error "AppName has stopped".

I am following the instructions and using the sample code. See below.
If I remove the subscribe code it runs without crashing and get to the then code after the register:
I can't see any console logs in the remote browser as it crashes.

 PushNotifications.register()
    .then(() => {
      console.log('success');
    })
    .catch((err) => alert(JSON.stringify(err)));

I am currently using the old version of the plugin with a different app on the same device and it works fine.

I might try going back to io.stewan.capacitor.fcm.FCMPlugin if I can't resolve this.
Does it work with the latest versions of Ionic and Capacitor?

To Reproduce
ionic build
npx cap copy android (previously have run sync)
npx cap open android
run (from android studio)

Expected behavior
App opens successfully.

Project:
"@capacitor/android": "^2.4.2",
"@capacitor/core": "2.4.2",
"@ionic-native/core": "^5.0.0",

Smartphone:

  • Device: Moto G6
  • OS: Android
  • Version 8.0.0

Code:

import '@capacitor-community/firebase-analytics';

import {
  Plugins,
  PushNotification,
  PushNotificationActionPerformed,
  PushNotificationToken,
  NotificationChannel,
  // PushNotificationChannel,
  AppState,
  AppUrlOpen
} from '@capacitor/core';

const { PushNotifications } = Plugins;

initializeApp() {

    this.platform.ready().then(() => {
      if (this.platform.is('capacitor')) {
        this.setupPushNotifications();
 });
  }

setupPushNotifications() {
    PushNotifications.register()
    .then(() => {
      //
      // Subscribe to a specific topic
      // you can use `FCMPlugin` or just `fcm`
      fcm
        .subscribeTo({ topic: 'test' })
        .then((r) => alert(`subscribed to topic`))
        .catch((err) => console.log(err));
    })
    .catch((err) => alert(JSON.stringify(err)));
}


MainActivity.java:
package nz.co.wekasolutions.nmtbc;

import android.os.Bundle;

import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import com.getcapacitor.community.firebaseanalytics.FirebaseAnalytics;
import com.getcapacitor.community.fcm.FCMPlugin;

import java.util.ArrayList;

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(FirebaseAnalytics.class);
      add(FCMPlugin.class);
    }});
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.