migrating from react-native-push-notification to react-native-firebase: ios onNotification not firing apns-push-type: alert
[ad_1]
I’m migrating from react-native-push-notification/react-native-community/push-notification-ios and am receiving the os notifications whereas the app is backgrounded/closed as I might anticipate, besides that when tapped, they don’t seem to be handed to js.
Based on the docs, RNfirebase must have {notification: {}, information: {}} keys, however our backend sends {alert: {}, information: {}}, which works with android and the earlier push notification library. Is there a technique to convert the notification earlier than it’s despatched to js? And why does it work on android?
Here’s what I’m utilizing to manually take a look at:
DEVICE_TOKEN=####################;
TOPIC=com.####.####;
CERTIFICATE_FILE_NAME=ios/push_cert.cer;
CERTIFICATE_KEY_FILE_NAME=ios/push_cert.pem;
APNS_HOST_NAME=api.sandbox.push.apple.com;
curl -v
--header "apns-topic: ${TOPIC}"
--header "apns-push-type: alert"
--cert "${CERTIFICATE_FILE_NAME}" --cert-type DER
--key "${CERTIFICATE_KEY_FILE_NAME}" --key-type PEM
--data '{ "Simulator Goal Bundle": "com.####.####", "aps": {"alert": {"title": "take a look at title","physique": "take a look at physique"},"sound": "default", "inAppOnly": false, "title": "take a look at title", "physique": "take a look at physique"},"information": { "distant": true, "notificationId": "D175CAE4-A7B3-4D71-8846-8518B76E9F87", "inAppOnly": false, "destinationType": "display screen", "durationInSeconds": 0, "entrance": "climate", "information": { "utmType": "display screen", "utmHeadline": "click on right here for more information" }, "title": "take a look at title", "physique": "take a look at physique" }, "title": "take a look at title", "physique": "take a look at physique"}'
--http2 https://${APNS_HOST_NAME}/3/system/${DEVICE_TOKEN}
#push-notification.helper.tsx
export const PushNotificationManager = () => {
if (ENVIRONMENT_SCREENSHOT_MODE) return null;
const dispatch = useDispatch();
const [token, setToken] = useState('');
const [onRegisterLastCalledTimestamp, setOnRegisterLastCalledTimestamp] = useState(0);
const prevToken = usePrevious(token);
useEffect(() => {
const u1 = messaging().onMessage(async remoteMessage => {
onNotification(remoteMessage, true);
console.log('A brand new FCM message arrived!', JSON.stringify(remoteMessage));
});
if (Platform.OS === 'ios') {
messaging().requestPermission().then(a => {
if (a)
messaging().getAPNSToken().then(async (b: string|null) => {
if (b)
setToken(b);
else {
await sleep(1000);
messaging().getAPNSToken().then(b2 => {
if (b2)
setToken(b2);
});
}
});
//messaging().getAPNSToken().then(b => {
// messaging().getToken().then(setToken);
// });
});
}
else
messaging().getToken().then(setToken);
const u2 = messaging().onTokenRefresh(a => {
if (Platform.OS === 'ios')
messaging().getAPNSToken().then(b => {
if (b)
setToken(b);
});
else
setToken(a);
});
return () => {
u1();
u2();
};
}, []);
useEffect(() => {
console.log('t', token);
(async () => {
const isNewToken = token !== prevToken;
const now = Date.now();
const isOver24HoursSinceLastCalled = now - onRegisterLastCalledTimestamp > MILLISECONDS_PER_DAY;
// so solely proceed if new token, or if it has been 24 hours since onRegister final referred to as
if (token && (isNewToken || isOver24HoursSinceLastCalled)) {
console.log('Push Notification', 'Registered token - ' + token);
setOnRegisterLastCalledTimestamp(now);
// Token refreshing, so app would not obtain notifications from legacy DoApp alert system
// This could solely be carried out as soon as, will lead to a brand new token being generated an onRegister referred to as once more
if (!await TGNStorage.get(STORAGE_KEYS.NOTIFICATIONS_HAS_REFRESHED_FIREBASE_INSTANCE)) {
console.log('Push Notification Renew token');
messaging().deleteToken();
await sleep(1000);
messaging().getToken();
await TGNStorage.set(STORAGE_KEYS.NOTIFICATIONS_HAS_REFRESHED_FIREBASE_INSTANCE, true);
return;
}
dispatch(notificationsActionRegisterPNSValue(token));
}
})();
}, [token, prevToken, onRegisterLastCalledTimestamp]);
return null;
};
export const configurePushNotifications = async () => {
console.log('configurepush');
if (ENVIRONMENT_SCREENSHOT_MODE) return;
const authorizationStatus = await messaging().requestPermission();
if (authorizationStatus === messaging.AuthorizationStatus.AUTHORIZED) {
console.log('Person has notification permissions enabled.');
} else if (authorizationStatus === messaging.AuthorizationStatus.PROVISIONAL) {
console.log('Person has provisional notification permissions.');
} else {
console.log('Person has notification permissions disabled');
}
// permissions: {
// alert: true,
// badge: true,
// sound: true,
// },
// requestPermissions: true,
// });
messaging().setBackgroundMessageHandler(async (...a) => {console.log('bgmessage', ...a); });
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification triggered app to open from background state:',
remoteMessage.notification,
);
//navigation.navigate(remoteMessage.information.kind);
});
messaging().getInitialNotification().then(async notification => {
const launchState = appPreviousState === 'background' ? AnalyticsLabel.Heat : AnalyticsLabel.Chilly;
appPreviousState="energetic";
if (notification)
onNotification(notification, false, launchState);
else {
appPreviousState="energetic";
await waitForStationApiData();
AnalyticsService.trackAppLaunch(launchState);
retailer.dispatch(generalActionSetInitialNavigationState(undefined));
}
});
messaging().hasPermission().then((...a) => console.log('haspermission', ...a));
};
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message dealt with within the background!', remoteMessage);
});
// configure as soon as, on app cold-start
configurePushNotifications();
#index.js
import {} from 'push-notification.helper';
import App from 'App';
AppRegistry.registerComponent(appName, () => App);
#App.tsx
export default class App extends Part {
render() {
<View>
<PushNotificationManager />
...
</View>
}
}
#AppDelegate.m
#import <Firebase.h>
...
- (BOOL)utility:(UIApplication *)utility didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
...
}
### eliminated this from the underside ###
// Required to register for notifications
- (void)utility:(UIApplication *)utility didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register occasion.
- (void)utility:(UIApplication *)utility didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification occasion. You have to name the completion handler after dealing with the distant notification.
- (void)utility:(UIApplication *)utility didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError occasion.
- (void)utility:(UIApplication *)utility didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification occasion.
- (void)utility:(UIApplication *)utility didReceiveLocalNotification:(UILocalNotification *)notification
{
[RNCPushNotificationIOS didReceiveLocalNotification:notification];
}
#podfile
...
$RNFirebaseAsStaticFramework = true
pod 'FirebaseCore', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true #firebase
...
#package deal.json
...
"@react-native-firebase/app": "^15.2.0",
"@react-native-firebase/messaging": "^15.2.0",
"react-native": "^0.66.4",
...
[ad_2]