react-native-firebaseでプッシュ通知を扱う
react-native-firebaseでプッシュ通知を扱う時のメモ
実装
基本的な実装はドキュメントへ
React Native Firebase - Simple Firebase integration for React Native
扱い方
プッシュ通知を押すとアプリが起動するが、そのパターンが3つある
- ① アプリが起動してない状態でプッシュ通知を押して起動される
- ② アプリは起動してるが、バックグラウンドにいるときにプッシュ通知を押して復帰
- ③ アプリの起動中にプッシュ通知が来た時
async componentDidMount() { // パーミッションを要求(iOS) await firebase.messaging().requestPermission() // デバイストークンを取得 firebase .messaging() .getToken() .then(fcmToken => { console.log(fcmToken) }) // 新しいトークンの生成がされた時 this.onTokenRefreshListener = firebase .messaging() .onTokenRefresh(fcmToken => { console.log(fcmToken) }) // ① プッシュ通知を押してクローズからの起動 const notificationOpen: NotificationOpen = await firebase .notifications() .getInitialNotification() if (notificationOpen) { console.log(notificationOpen) } // ② プッシュ通知を押してバックグラウンドからの復帰 this.notificationOpenedListener = firebase .notifications() .onNotificationOpened(notificationOpen => { console.log(notificationOpen) }) // ③ アプリが起動中にプッシュ通知が来た時 this.notificationListener = firebase .notifications() .onNotification(notification => { console.log(notification) }) } // リスナーを解除 componentWillUnmount() { this.onTokenRefreshListener() this.notificationOpenedListener() this.notificationListener() }
多分、これでほとんどのパターンをカバー出来るはず