Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notification iOS with image not showing with FCM #2432

Closed
1 of 6 tasks
idir-s opened this issue Aug 1, 2019 · 49 comments
Closed
1 of 6 tasks

Notification iOS with image not showing with FCM #2432

idir-s opened this issue Aug 1, 2019 · 49 comments
Labels
Type: Stale Issue has become stale - automatically added by Stale bot

Comments

@idir-s
Copy link

idir-s commented Aug 1, 2019

Issue

I want to receive notification with an image from FCM but the image is not display in the notification banner on iOS but work on Android.


Project Files

iOS

Click To Expand

ios/Podfile:

  • I'm not using Pods
  • I'm using Pods and my Podfile looks like:
    pod 'Firebase/Core', '~> 6.3.0'
    pod 'GoogleIDFASupport', '~> 3.14.0'
    pod 'Firebase/Messaging', '~> 6.3.0'
    pod 'RNFirebase', :path => '../node_modules/react-native-firebase/ios'

AppDelegate.m:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}


Android

Click To Expand

Have you converted to AndroidX?

  • my application is an AndroidX application?
  • I am using android/gradle.settings jetifier=true for Android compatibility?
  • I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// N/A

android/app/build.gradle:

// N/A

android/settings.gradle:

// N/A

MainApplication.java:

// N/A

AndroidManifest.xml:

<!-- N/A -->


Environment

Click To Expand

react-native info output:

react-native : 0.60.4
  • Platform that you're experiencing the issue on:
    • iOS
  • **react-native-firebase
    • 5.5.6


Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

@idir-s idir-s closed this as completed Aug 1, 2019
@idir-s idir-s reopened this Aug 1, 2019
@booboothefool
Copy link

booboothefool commented Aug 4, 2019

I'm also having this problem. After attaching an image to a notification in Firebase, I would have expected the puppy to show up in the notification, but there's only text. Are there any extra steps or iOS code that has to be added to enable this functionality?

Screenshot 2019-08-04 17 48 43

@Ehesp
Copy link
Member

Ehesp commented Aug 5, 2019

This should be something handled automatically by the device. I guess, it would be an SDK version update?

@LuisRodriguezLD
Copy link
Contributor

I can see this was implemented back in April for Android but I can't find something similar on iOS

@LuisRodriguezLD
Copy link
Contributor

Apparently we need to create an extension -> docs here.

Would be great if react-native-firebase could do this automatically :)

@booboothefool
Copy link

@LuisRodriguezLD Were you able to get that notification service extension set up properly? If so, could you provide some steps?

@LuisRodriguezLD
Copy link
Contributor

LuisRodriguezLD commented Aug 11, 2019

Yes! I made it work :)
Here is what I did:

  1. Create a new Notification Service Extension
    In Xcode, File -> New -> Target -> Notification Service Extension
    Name it and save it ( I used NotificationServiceExtension but you can use whatever )

  2. This new target will need the pods as well, so in your pod file add

target 'NotificationServiceExtension' do
    pod 'Firebase/Messaging', '~> 6.3.0'
end

(Don't forget to pod install)

  1. Edit your NotificationService.m file in the NotificationServiceExtension folder, this was created automatically in step 1.

Import RNFirebaseMessaging at the top

#import "RNFirebaseMessaging.h"

And replace

self.contentHandler(self.bestAttemptContent);

with

[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

This video can get you started in step 1.
This page has instructions on step 3.

If you get stuck let me know.
Please note, step 1 automatically adds a deployment target version. Adjust according to your needs.

@booboothefool
Copy link

booboothefool commented Aug 11, 2019

I am running into some problems.

Screenshot 2019-08-11 00 25 54

react: 16.3.1
react-native: https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz
react-native-firebase: ~5.4.0

pod 'RNFirebase', :path => '../node_modules/react-native-firebase/ios'
pod 'Firebase/Core', '~> 5.4.0'
pod 'Firebase/Auth', '~> 5.4.0'
pod 'Firebase/Messaging', '~> 5.4.0'
pod 'Firebase/Storage', '~> 5.4.0'
pod 'Firebase/DynamicLinks', '~> 5.4.0'

Ugh I'm stuck on 5.4.0 and this might have to do with it? firebase/firebase-ios-sdk#1503

@LuisRodriguezLD
Copy link
Contributor

Yeah. I highly recommend you upgrade react-native-firebase to 5.5.6 which has the firebase sdk in 6.3.0

@stale
Copy link

stale bot commented Sep 8, 2019

Hello 👋, to help manage issues we automatically close stale issues.
This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs.
Thank you for your contributions.

@stale stale bot added the Type: Stale Issue has become stale - automatically added by Stale bot label Sep 8, 2019
@ThanhQuang1410
Copy link

@LuisRodriguezLD thanks for your solution but I still get some glitch here. When app in background or foreground, my notification display perfectly with image. But when app is open image dose not show. Do you have any solution for that?
Thanks for your support

@stale stale bot removed the Type: Stale Issue has become stale - automatically added by Stale bot label Sep 11, 2019
@LuisRodriguezLD
Copy link
Contributor

@ThanhQuang1410 Sorry, I do not have a current solution for when the app is open. I am pretty sure it's a very similar approach.

I'll try to get an example running today but no promises. Feel free to DM me.

@sakinaboriwala
Copy link

@LuisRodriguezLD Awesome. Did you get a chance to try? I am facing a similar issue on Android as well. When the App is open expandable Notifications don't come, even if it's text. The Notification is received but it's not expandable.

@joshcho96
Copy link

joshcho96 commented Sep 18, 2019

@LuisRodriguezLD Awesome. Did you get a chance to try? I am facing a similar issue on Android as well. When the App is open expandable Notifications don't come, even if it's text. The Notification is received but it's not expandable.

In android handle it by doing notification.android.setLargeIcon(IMAGE_URL);
and pass image url as data

@NikitaPFE
Copy link

Yes! I made it work :)
Here is what I did:

  1. Create a new Notification Service Extension
    In Xcode, File -> New -> Target -> Notification Service Extension
    Name it and save it ( I used NotificationServiceExtension but you can use whatever )
  2. This new target will need the pods as well, so in your pod file add
target 'NotificationServiceExtension' do
    pod 'Firebase/Messaging', '~> 6.3.0'
end

(Don't forget to pod install)

  1. Edit your NotificationService.m file in the NotificationServiceExtension folder, this was created automatically in step 1.

Import RNFirebaseMessaging at the top

#import "RNFirebaseMessaging.h"

And replace

self.contentHandler(self.bestAttemptContent);

with

[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

This video can get you started in step 1.
This page has instructions on step 3.

If you get stuck let me know.
Please note, step 1 automatically adds a deployment target version. Adjust according to your needs.

Сan you show an example of your code?
When i try to add #import "RNFirebaseMessaging.h" i have error "file not found".
Рow did you modify the AppDelegate.m and AppDelegate.h files?

I use Firebase/Messaging', '~> 6.3.0'
and react native 0.59.9

@LuisRodriguezLD
Copy link
Contributor

LuisRodriguezLD commented Sep 19, 2019

@NikitaPFE there is not actual code besides that, it's just configuration.

file not found could be because you did not install the pods. did you follow step 2? Don't forget you need to pod install

@NikitaPFE
Copy link

@LuisRodriguezLD
Yes, I did pod install

You do not know whether to remove these methods from the AppDelegate.m?

Screen Shot 2019-09-19 at 19 50 54

@sakinaboriwala
Copy link

sakinaboriwala commented Sep 19, 2019

@NikitaPFE There is no need to remove that code from Appdelegate.m

To resolve file not found error, follow these steps:

Go to NotificationService Target -> Build Settings -> Search Header paths and add ->

$(SRCROOT)/../node_modules/react-native-firebase/ios/RNFirebase/messaging

Refer #632 (comment) for the same.

@stale
Copy link

stale bot commented Oct 17, 2019

Hello 👋, to help manage issues we automatically close stale issues.
This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs.
Thank you for your contributions.

@stale stale bot added the Type: Stale Issue has become stale - automatically added by Stale bot label Oct 17, 2019
@stale
Copy link

stale bot commented Nov 1, 2019

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

@stale stale bot closed this as completed Nov 1, 2019
@Dhavalmaheta
Copy link

I'm also having this problem. After attaching an image to a notification in Firebase, I would have expected the puppy to show up in the notification, but there's only text. Are there any extra steps or iOS code that has to be added to enable this functionality?

Screenshot 2019-08-04 17 48 43

any solution you got for this ?

@Anshuman71
Copy link

Yes! I made it work :)
Here is what I did:

  1. Create a new Notification Service Extension
    In Xcode, File -> New -> Target -> Notification Service Extension
    Name it and save it ( I used NotificationServiceExtension but you can use whatever )
  2. This new target will need the pods as well, so in your pod file add
target 'NotificationServiceExtension' do
    pod 'Firebase/Messaging', '~> 6.3.0'
end

(Don't forget to pod install)

  1. Edit your NotificationService.m file in the NotificationServiceExtension folder, this was created automatically in step 1.

Import RNFirebaseMessaging at the top

#import "RNFirebaseMessaging.h"

And replace

self.contentHandler(self.bestAttemptContent);

with

[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

This video can get you started in step 1.
This page has instructions on step 3.

If you get stuck let me know.
Please note, step 1 automatically adds a deployment target version. Adjust according to your needs.

@LuisRodriguezLD thanks for your help. Your solution worked like a charm and now I can send push with images from the console. Can you please share your push notification code, the payload you send from your server.

@casualcoder404
Copy link

Yes! I made it work :)
Here is what I did:

  1. Create a new Notification Service Extension
    In Xcode, File -> New -> Target -> Notification Service Extension
    Name it and save it ( I used NotificationServiceExtension but you can use whatever )
  2. This new target will need the pods as well, so in your pod file add
target 'NotificationServiceExtension' do
    pod 'Firebase/Messaging', '~> 6.3.0'
end

(Don't forget to pod install)

  1. Edit your NotificationService.m file in the NotificationServiceExtension folder, this was created automatically in step 1.

Import RNFirebaseMessaging at the top

#import "RNFirebaseMessaging.h"

And replace

self.contentHandler(self.bestAttemptContent);

with

[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

This video can get you started in step 1.
This page has instructions on step 3.

If you get stuck let me know.
Please note, step 1 automatically adds a deployment target version. Adjust according to your needs.

I implemented these steps in my code. However when I send =>

{
"to": "dWB537Nz1GA:APA91bHIjJ5....",
"content_available": true,
"mutable_content": true,
"data":
{
"message": "Offer!",
"mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
},
"notification":
{
"body": "Enter your message",
"sound": "default"
}
}

I am still not able to see the image in the notification.

@pilot4u
Copy link

pilot4u commented Jan 24, 2020

did anyone solved this issue I'm struggling with the same one
I added :
target 'NotificationServiceExtension' do
pod 'Firebase/Messaging', '~> 6.3.0'
end
to pod file and did pod install
as well edited NotificationService.m file
and replaced self.contentHandler(self.bestAttemptContent);
with:
[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent
withContentHandler:contentHandler];

but cannot receive notification after successfully sending following FCM POST
"notification": { "title": “test”, "body": “test”, "icon": "", "sound": "" }, "apns": { "payload": { "aps": { "mutable-content": 1 }, "mediaUrl": "<img url>", "mediaType": "image" }, "fcm_options": { "image": “<img url>“ } }, "data": { <custom json> }, "to": “<fcm token>” }

please note that this message is received when the application is in the foreground.
but nothing is received when the app in the background or closed
please help us to resolve this issue

@gianpaj
Copy link
Contributor

gianpaj commented Feb 6, 2020

If you have this iOS app build error:

'openURL:options:completionHandler:' is unavailable: not available on iOS (App Extension

you have to add this at the end of your Podfile:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'NO'
    end
  end
end

from: facebook/react-native#25792 (comment)

@pranav-jayadev
Copy link

I have tried this, and am getting some error like the provisioning profile is not matching. Here my question is after adding the Notification service extension do we need to create another provisioning profile for this bundle id?

@ali-tit
Copy link

ali-tit commented Feb 24, 2020

after adding a NotificationServiceExtension please Check your deployment target on Service Extension.

by default the Extension deployment target is set to iOS 13.1 ( depending on your sdk version ), so you need a device with same iOS version OR you have to choose a lower value to match your device iOS
apns

@davidepalazzo
Copy link
Contributor

Import RNFirebaseMessaging at the top
#import "RNFirebaseMessaging.h"

For people using RNF 5 or greater change the import to #import “FirebaseMessaging.h”.

@yash-atreya
Copy link

Yes! I made it work :)
Here is what I did:

  1. Create a new Notification Service Extension
    In Xcode, File -> New -> Target -> Notification Service Extension
    Name it and save it ( I used NotificationServiceExtension but you can use whatever )
  2. This new target will need the pods as well, so in your pod file add
target 'NotificationServiceExtension' do
    pod 'Firebase/Messaging', '~> 6.3.0'
end

(Don't forget to pod install)

  1. Edit your NotificationService.m file in the NotificationServiceExtension folder, this was created automatically in step 1.

Import RNFirebaseMessaging at the top

#import "RNFirebaseMessaging.h"

And replace

self.contentHandler(self.bestAttemptContent);

with

[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

This video can get you started in step 1.
This page has instructions on step 3.

If you get stuck let me know.
Please note, step 1 automatically adds a deployment target version. Adjust according to your needs.

This did not work for me.
Build was successful but it still didn't work

@jagwingchoy
Copy link

after adding a NotificationServiceExtension please Check your deployment target on Service Extension.

by default the Extension deployment target is set to iOS 13.1 ( depending on your sdk version ), so you need a device with same iOS version OR you have to choose a lower value to match your device iOS
apns

Thanks you make my day!!

@Daha62
Copy link

Daha62 commented Oct 21, 2020

Import RNFirebaseMessaging at the top
#import "RNFirebaseMessaging.h"

For people using RNF 5 or greater change the import to #import “FirebaseMessaging.h”.

I've one everything that was written above, but got an error

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FIRMessaging", referenced from:
      objc-class-ref in NotificationService.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

react-native v0.63.3
RNF is greater than 5

Here is a part of my NotificationService.m

#import "NotificationService.h"
#import "FirebaseMessaging.h"

@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    // Modify the notification content here...
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
    
    [[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];
}

@end

Also I have in my podFile

  target 'NotificationService' do
    pod 'Firebase/Messaging', '~> 6.30.0'
  end

Any ideas?

@mikehardy
Copy link
Collaborator

@Daha62 as near as I can tell this is a "welcome to Xcode 12 and Apple SIlicon support in Xcode" bug. It's not related specifically to our module. You'll find all sorts of conflicting advice on stack overflow about it and you can see the PR here for a workaround (not a great solution) to a similar issue. It's going to be project-specific in the end I think #4401

@haduytrl
Copy link

after adding a NotificationServiceExtension please Check your deployment target on Service Extension.

by default the Extension deployment target is set to iOS 13.1 ( depending on your sdk version ), so you need a device with same iOS version OR you have to choose a lower value to match your device iOS
apns

Thank you very much, you just save my whole day. I appreciate it

@curiousdustin
Copy link

Another tip for those trying to cruise through this thing that should be handled automatically...

The NotificationService.m is created with boilerplate code already in it.

You probably want to remove or edit this line, which modifies the notification title:

self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
@Hyllesen
Copy link

Hyllesen commented Apr 7, 2021

For anyone with RNFirebaseMessaging.h file not found error or errors with #Import "FirebaseMessaging.h" use
@import Firebase instead

@anhquan291
Copy link

anhquan291 commented Apr 14, 2021

Yes! I made it work :)
Here is what I did:

  1. Create a new Notification Service Extension
    In Xcode, File -> New -> Target -> Notification Service Extension
    Name it and save it ( I used NotificationServiceExtension but you can use whatever )
  2. This new target will need the pods as well, so in your pod file add
target 'NotificationServiceExtension' do
    pod 'Firebase/Messaging', '~> 6.3.0'
end

(Don't forget to pod install)

  1. Edit your NotificationService.m file in the NotificationServiceExtension folder, this was created automatically in step 1.

Import RNFirebaseMessaging at the top

#import "RNFirebaseMessaging.h"

And replace

self.contentHandler(self.bestAttemptContent);

with

[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

This video can get you started in step 1.
This page has instructions on step 3.
If you get stuck let me know.
Please note, step 1 automatically adds a deployment target version. Adjust according to your needs.

This did not work for me.
Build was successful but it still didn't work

Hi there, I'm facing the same problem here. Already done all the steps and build successfully. Did you find a solution? Thanks a lot

@lauro-cesar
Copy link

Don't miss this detail: Check Frameworks and Libraries and make sure the extension is embedded.

Screen Shot 2021-04-30 at 21 34 57

@OsamaShakir-bot
Copy link

After 5 hours or struggle finally, did it follow this link it has step by step guide
https://rnfirebase.io/messaging/ios-notification-images

after then check the development target of your extension

@vipu-sa
Copy link

vipu-sa commented Jan 4, 2022

https://rnfirebase.io/messaging/ios-notification-images

I am following this link for the notification with the image in iPhone, but the image is not getting with notification.

I am sharing the details of current versions which are used in my project.
"react-native": "0.62.2",
"@react-native-firebase/app": "^8.4.0",
"@react-native-firebase/messaging": "^7.8.1",
Firebase/Messaging (6.34.0) in Podfile.lock
In project, Deployment Info, iOS version is 14.4
In my iPhone device version is 14.7.1

Getting build fail issue when inserting the below line in NotificationService file.
#import "FirebaseMessaging.h"
[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];

Please help to solve this issue.

@ydv0121
Copy link

ydv0121 commented Feb 11, 2022

after adding a NotificationServiceExtension please Check your deployment target on Service Extension.

by default the Extension deployment target is set to iOS 13.1 ( depending on your sdk version ), so you need a device with same iOS version OR you have to choose a lower value to match your device iOS apns

after spend many hours.this worked like a charm.
thanks

@congduong97
Copy link

Any solution for #import "RNFirebaseMessaging.h" not found?, thanks

@mikehardy
Copy link
Collaborator

@congduong97 it is not polite to post unrelated comments to other people's issues

@congduong97
Copy link

@mikehardy Sorry,
I had this problem while following the instructions and I saw that someone had the same problem as me

@JeanHules
Copy link

After a bit of struggling, Xcode set my extension iOS version to the latest while the main app's version was set to 12.4. Changing the extension to 12.4, the image comes through.

@isaacbatst
Copy link

isaacbatst commented Sep 21, 2023

I had to do it a bit different as suggested here

target 'ImageNotification' do
  use_frameworks! :linkage => :static
  
  pod 'Firebase/Messaging', '~> VERSION'
end
@DaveTolulope22
Copy link

Notification image only shows when in the app is in the background not when the app is in the Foreground how do I solve this ?

@Djain1764
Copy link

Notification image only shows when in the app is in the background not when the app is in the Foreground how do I solve this ?

hey @DaveTolulope22 , are you able to make image notifications work ??
I am not even able to make it work for background notifications, can you please help me on that, can you tell me what reference you followed exactly !!

@ehtishamali042
Copy link

after adding a NotificationServiceExtension please Check your deployment target on Service Extension.

by default the Extension deployment target is set to iOS 13.1 ( depending on your sdk version ), so you need a device with same iOS version OR you have to choose a lower value to match your device iOS apns

amazing amazing amazing

@danishsaleem0
Copy link

working in forground but not in background how to solve this?
here is my notification-service
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import {Platform} from 'react-native';

class LocalNotificationService {
configure = onOpenNotification => {
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {},

  // (required) Called when a remote is received or opened, or local notification is opened
  onNotification: function (notification) {
    if (!notification?.data) {
      return;
    }
    notification.userInteraction = true;
    onOpenNotification(
      Platform.OS === 'ios' ? notification.data.item : notification.data,
    );

    if (Platform.OS === 'ios') {
      notification.finish(PushNotificationIOS.FetchResult.NoData);
    }
  },

  // (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
  onAction: function (notification) {
    console.log('ACTION:', notification.action);
    console.log('NOTIFICATION:', notification);
  },

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError: function (err) {
    console.error(err.message, err);
  },

  permissions: {
    alert: true,
    badge: true,
    sound: true,
  },

  popInitialNotification: true,
  requestPermissions: true,
});

};
unRegister = () => {
PushNotification.unregister();
};

showNotification = (id, title, message, data = {}, options = {}) => {
PushNotification.localNotification({
/* Android only Properties*/
...this.buildAndroidNotification(id, title, message, data, options),
/* IOS and Android properties*/

  ...this.buildIOSNotification(id, title, message, data, options),
  /* IOS and Android properties */
  title: title || '',
  message: message || '',
  playSound: options.playSound || false,
  soundName: options.soundName || 'default',
  channelId: 'mindnourishment',
  userInteraction: false, // BOOLEAN: If the notification was opened by the user from the notification area or not
});

};
buildAndroidNotification = (id, title, message, data = {}, options = {}) => {
return {
id: id || 1,
autoCancel: true,
largeIcon: options.largeIcon || 'ic_launcher',
smallIcon: options.smallIcon || 'ic_notification',
bigText: message || '',
subText: title || '',
vibrate: options.vibrate || true,
vibration: options.vibration || 300,
priority: options.priority || 'high',
importance: options.importance || 'high', // (optional) set notifications importance
data: data,
};
};

buildIOSNotification = (id, title, message, data = {}, options = {}) => {
console.log(data, 'data');
return {
alertAction: options.alertAction || 'view',
category: options.category || '',
userInfo: {
id: id,
item: data,
// image: data?.data?.fcm_options?.image || null,
},
};
};

createNotificationChannel = () => {
PushNotification.createChannel({
channelId: 'mindnourishment',
channelName: 'mindnourishment',
channelDescription: 'Mindnourishment Channel Description ',
importance: 4, // 4 = Max, 3 = High, 2 = Default, 1 = Low, 0 = None
vibration: true,
});
};
cancelAllLocalNotifications = () => {
{
PushNotification.cancelAllLocalNotifications();
}
};
removeDeliveredNotificationByID = notificationId => {
console.log(
'[LocalNotificationService] removeDeliveredNotificationByID: ',
notificationId,
);
PushNotification.cancelLocalNotifications({id: ${notificationId}});
};
}

export const localNotificationService = new LocalNotificationService();

and fcm-service
import messaging from '@react-native-firebase/messaging';
import {Platform} from 'react-native';

class FCMService {
register = (onRegister, onNotification, onOpenNotification) => {
this.checkPermission(onRegister);
this.createNotificationsListeners(
onRegister,
onNotification,
onOpenNotification,
);
};

registerAppWithFCM = async () => {
if (Platform.OS === 'ios') {
await messaging().registerDeviceForRemoteMessages();
await messaging().setAutoInitEnabled(true);
}
};

checkPermission = onRegister => {
messaging()
.hasPermission()
.then(enabled => {
if (enabled) {
// User has permission
this.getToken(onRegister);
} else {
// User doesn't have permission
this.requestPermission();
}
})
.catch(error => {
console.log('[FCMService] Permission rejected', error);
});
};

getToken = onRegister => {
messaging()
.getToken()
.then(fcmToken => {
if (fcmToken) {
onRegister(fcmToken);
} else {
console.log('[FCMService] user does not have a device token');
}
})

  .catch(error => {
    console.log('[FCMService] getToken rejected', error);
  });

};

requestPermission = onRegister => {
messaging()
.requestPermission()
.then(() => {
this.getToken(onRegister);
})
.catch(error => {
console.log('[FCMService] Request permission rejected');
});
};

deleteToken = () => {
console.log('[FCMService] deleteToken');
messaging()
.deleteToken()
.catch(error => {
console.log('[FCMService] Delete token error ', error);
});
};

createNotificationsListeners = (
onRegister,
onNotification,
onOpenNotification,
) => {
// When the application is running ,but in background
messaging().onNotificationOpenedApp(remoteMessage => {
if (remoteMessage) {
const notification = remoteMessage.notification;
console.log(notification, 'remoteMessage');
onOpenNotification(remoteMessage);
}
});

messaging().setBackgroundMessageHandler(async remoteMessage => {
  if (remoteMessage) {
    const notification = remoteMessage;
    console.log(notification);
    onOpenNotification(remoteMessage);
  }
});
// when the application is opened from a quite state.
messaging()
  .getInitialNotification()
  .then(remoteMessage => {
    if (remoteMessage) {
      const notification = remoteMessage.notification;
      onOpenNotification(remoteMessage);
    }
  });
// Foreground state messages
this.messageListener = messaging().onMessage(async remoteMessage => {
  if (remoteMessage) {
    let notification = null;
    if (Platform.OS === 'ios') {
      notification = remoteMessage;
    } else {
      notification = remoteMessage;
    }
    onNotification(notification);
  }
});

// Triggered when have new token
messaging().onTokenRefresh(fcmToken => {
  console.log('[FCMService] New token refresh: ', fcmToken);
  onRegister(fcmToken);
});

};

unRegister = () => {
this.messageListener();
};
}

export const fcmService = new FCMService();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Stale Issue has become stale - automatically added by Stale bot