Reputation: 690
I already implement the push notification on my app and its working. right now when someone click on the notification the app is opening.
In addition for this I want to do another thing when a user press on the notification:
1. post request to the server(I want to keep a record that someone click on the notification).
2. open the app like now
my question is how can I do that? I need to implement it on the server side or on the react native side? If someone has tutorial of how to do it (for android and iOS or even for one of them) it will help a lot!
I was looking a lot but didn't find something which can help me.
Im adding my implement:
on the server side:
public void sendNotification(String token,String msg) {
// This registration token comes from the client FCM SDKs.
String registrationToken =token;
// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(new com.google.firebase.messaging.Notification( null,msg))
.setToken(registrationToken).setApnsConfig(ApnsConfig.builder().setAps(Aps.builder().setSound("default").build()).build()).setAndroidConfig(AndroidConfig.builder().setNotification(AndroidNotification.builder().setSound("default").build()).build())
.build();
try {
String response = FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException e) {
}
}
on react native: for android:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static int count = 0;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
String click_action= remoteMessage.getNotification().getClickAction();
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
//This method is only generating push notification
private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
PendingIntent contentIntent = null;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
//.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
count++;
}
}
on iOS:
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
[FIRApp configure];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"**"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
//NSLog(@"push-notification received: %@", notification)
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[RCTPushNotificationManager didReceiveLocalNotification:notification];
}
when im getting token:
setNotification(userid){
const version = DeviceInfo.getUniqueID()
firebase.app().onReady().then(app => {
const again= AsyncStorage.getItem('deviceToken', (err, token) => {
this.props.profileActions.updateLoginTrack()
console.log("checkingTokenFromLogin",token)
console.log('version', version)
if(token==null) {
console.log("tokenNull")
app.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
console.log('fcmtokenApp', fcmToken)
this.saveDeviceToken(fcmToken)
//need to save in database too
let deviceTokenData = {
userId: userid,
deviceUniqueId: version,
deviceToken: fcmToken,
}
this.props.profileActions.updateDeviceToken(deviceTokenData)
} else {
console.log('error with getting token')
}
})
}
Thank you for the help
Upvotes: 3
Views: 11184
Reputation: 690
Solution:
the solution I found is
I used only the function
getInitialNotification()
with this function you can trigger the notification when the app close.
If you want to to trigger the notification when the app is in the background you want use this function:
onNotificationOpened()
with this function I didn't use the listener(it didn't work for me), I only use this function in
componentDidMount
and not in
componentWillUnmount
hope it will help someone and save some time for you
Upvotes: 2