How to receive firebase push notification in react native IOS? - react-native

Is there a way on how to receive push notification payload in IOS? In android it works by doing it this way:
firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
});
however it does not work in ios. It tried:
firebase.notifications().displayNotification((notification) => {
console.log(notification);
});
or
firebase.notifications().onNotification((notification) => {
console.log(notification);
});
still nothing works. Thanks

Nevermind, I sorted it out by call it this way:
firebase.notifications().onNotificationDisplayed((notification: Notification) => {
console.log(notification);
});
firebase.notifications().onNotification((notification: Notification) => {
console.log(notification);
});

Related

How to get pushToken from react-native-onesignal?

1 year ago, I got pushToken successfully in my react-native app. But right now official website sample code was changed, so I couldn't find any code how to get pushToken.
This is the code I used last year. (Class component)
constructor(props) {
super(props);
...
OneSignal.addEventListener('ids', this.onIds);
}
componentWillUnmount() {
OneSignal.removeEventListener('received', this.onReceived);
OneSignal.removeEventListener('opened', this.onOpened);
OneSignal.removeEventListener('ids', this.onIds);
}
onIds(device) {
console.log('Device info: ', device); // I got pushToken here successfully last year.
}
This is my current code. (Functional component)
useEffect(() => {
// OneSignal Init Code
OneSignal.setAppId("My-OneSignal-Key");
OneSignal.setLogLevel(6, 0);
// END OneSignal Init Code
// Prompt for push on iOS
OneSignal.promptForPushNotificationsWithUserResponse(response => {
console.log("Prompt response:", response);
});
// Method for handling notifications received while app in foreground
OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
console.log("OneSignal: notification will show in foreground:", notificationReceivedEvent);
let notification = notificationReceivedEvent.getNotification();
console.log("notification: ", notification);
const data = notification.additionalData
console.log("additionalData: ", data);
// Complete with null means don't show a notification.
notificationReceivedEvent.complete(notification);
});
// Method for handling notifications opened
OneSignal.setNotificationOpenedHandler(notification => {
console.log("OneSignal: notification opened:", notification);
});
}
But now, where should I get pushToken?
I found this in the doc:
const deviceState = await OneSignal.getDeviceState();
so I think it could be something like:
const deviceState = (await OneSignal.getDeviceState()).pushToken;
Look inside the notification object of setNotificationOpenedHandler or setNotificationWillShowInForegroundHandler.

react-native, Android Freshchat isFreshchatNotification not handling firebase remote message

I'm trying to integrate react-native-freshchat-sdk to react native app, but when firebase remote message is coming, freshchatNotification is 0, but it should be 1. Even if I pass notification to Freshchat.handlePushNotification nothing happens. I assume Freshchat.handlePushNotification should navigate the user to the conversation
Actual result
freshchatNotification is 0 if it is fcm notification
Freshchat.handlePushNotification(notification) does nothing
Expected result:
freshchatNotification should be equal 1 if it is fcm notification
Freshchat.handlePushNotification(notification) should navigate the user to the chat
import messaging from '#react-native-firebase/messaging'
import { Freshchat} from 'react-native-freshchat-sdk'
//...
useEffect(() => {
const unsubscribe = messaging().onMessage(notification => {
Freshchat.isFreshchatNotification(notification, (freshchatNotification) => {
Freshchat.handlePushNotification(notification);
if (freshchatNotification) {
Freshchat.handlePushNotification(notification);
} else {//...}
})
});
return unsubscribe
}, [])
See push notification payload below:
Faced similar issue, worked by passing notification.data instead of direct notification object to Freshchat
useEffect(() => {
const unsubscribe = messaging().onMessage(notification => {
Freshchat.isFreshchatNotification(notification.data, (freshchatNotification) => {
Freshchat.handlePushNotification(notification);
if (freshchatNotification) {
Freshchat.handlePushNotification(notification.data);
} else {//...}
})
});
return unsubscribe
}, [])

orientation change listener in expo react native not firing?

i want to detect the current orientation of device in expo react native, this is my code that doesn't work:
import {
Dimensions,
} from 'react-native';
import * as ScreenOrientation from 'expo-screen-orientation';**
const App = () => {
...
useEffect(() => {
const isPortrait = () => {
const dimension = Dimensions.get('screen');
return dimension.height >= dimension.width;
};
Dimensions.addEventListener('change', () => {
const orientation = isPortrait() ? 'portrait' : 'landscape';
console.log('Dimensions orientation', orientation);
});
ScreenOrientation.addOrientationChangeListener((e) => {
console.log('e ', e);
});
}, []);
how ever when i rotate the device there is no logs so it's not firing?
This works for me:
const [orientation, setOrientation] = useState(
ScreenOrientation.Orientation.PORTRAIT_UP
);
useEffect(() => {
// set initial orientation
ScreenOrientation.getOrientationAsync().then((info) => {
setOrientation(info.orientation);
});
// subscribe to future changes
const subscription = ScreenOrientation.addOrientationChangeListener((evt) => {
setOrientation(evt.orientationInfo.orientation);
});
// return a clean up function to unsubscribe from notifications
return () => {
ScreenOrientation.removeOrientationChangeListener(subscription);
};
}, []);
You should set your orientation field as default in your app.json / app.config.js. The app is locked to the specified orientation if this field is set to another value.
Related doc is here:
https://docs.expo.dev/versions/v46.0.0/config/app/#orientation
This is the line that doesn't do anything. Broken, bugged, POS? All of the above?
ScreenOrientation.addOrientationChangeListener((e) => {
console.log(e);
});
I had this same issue. The listener function was never firing.
Adding expo-sensors to my project seems to have fixed the callback for me. I think expo-screen-orientation might depend on expo-sensors
Steps for adding:
npx expo install expo-sensors
Rebuild your expo development client. (For me that command is eas build --profile simulator, but that will depend on your eas config)
After that, the listener callback function started firing.
Here's a code snippet of where I add the listener:
useEffect(() => {
ScreenOrientation.addOrientationChangeListener((e) => {
console.log(e)
})
}, [])
You're using the wrong package.
From the expo-screen-orientation docs:
Screen Orientation is defined as the orientation in which graphics are painted on the device. ... For physical device orientation, see the orientation section of Device Motion.

how to set small Icon when pushing message in nodejs

I'm usnig fcm for notification in nodejs. So I made this And when I push message from nodejs to android, I got message well. When the app is running, I can get the small Icon image. But when the app is not running, I got the notification with no image. how can I get the push message with image when the app is in background? here is my nodejs code
let pushMsg = req.body.pushMsg;
let groupName = req.body.groupName;
console.log(groupName)
var condition = "'"+groupName+"' in topics"; //"'all' in topics || 'industry-tech' in topics";
var message = {
notification: {
title: 'schedule updated',
body: pushMsg,
image:'./upload/haiilogo.png'
},
condition: condition
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
I solved. I added manifest to default icon like this
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/haiilogo" />

Send push notification using Expo

I am trying to send push notification using Expo, and I receive it. But there is no vibrate or sound and no pop up as well on my device. I am using Galaxy S9 with Android 9. I have not tried on Iphone yet.
Push notification is sent by nodejs and the user who installed the app will receive the push notification. User expo token is saved in firebase database. I succeed to save and fetch the token.
Below is from expo app
class App extends Component {
componentWillMount() {
firebase.initializeApp(config);
this.registerForPushNotificationsAsync();
}
async registerForPushNotificationsAsync(){
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (Platform.OS === 'android') {
Notifications.createChannelAndroidAsync('chat-messages', {
name: 'Chat messages',
sound: true,
priority: 'high', // was max
vibrate: [0, 250, 250, 250],
});
}
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
Below is from nodejs server-side
function sendMessage(to, title, body) {
const expo = new Expo();
let messages = [];
messages.push({
to, // Expo user token
body,
data: { withSome: 'data' },
ios: {
sound: true
},
android: {
"channelId": "chat-messages" //and this
}
})
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
(async () => {
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
tickets.push(...ticketChunk);
} catch (error) {
console.error(error);
}
}
})();
}
Also could we redirect to web page when user click the push notification?
I see three problems on your backend code ( expo push notification docs for reference https://docs.expo.io/versions/latest/guides/push-notifications/):
According to the docs, there should be no ios or android properties on the request body;
sound should be either 'default' or null, instead of true;
You created the notification channel on the device, but when you send the notification, you forgot to tell which channel you are sending to.
All that said, your code that calls the expo push notifications api should look something like this:
messages.push({
to, // Expo user token
title: 'some title', //it is good practice to send title, and it will look better
body,
data: { withSome: 'data' },
priority: 'high', //to make sure notification is delivered as fast as possible. see documentation for more details
sound: true, //for iOS devices and android below 8.0
channelId: 'chat-messages', //for devices on android 8.0 and above
})
I hope this helps.