LoginSignup
18
15

More than 5 years have passed since last update.

ReactNativeでのiOSプッシュ通知の実装方法

Posted at

React Nativeでプッシュ通知機能追加方法を紹介します。

ライブラリ

プッシュ通知を実装するために、react-native-push-notificationを使います。
zo0r/react-native-push-notification: React Native Local and Remote Notifications
このライブラリはiOS・Android両方対応してますが、今回はiOSのみ設定します。

インストール

初めに、ライブラリをインストールします。

 yarn add react-native-push-notification

リンク

利用するためには、手動でリンクさせる必要があります。
Linking Libraries · React Native を参考にリンクさせます。

実装

プッシュ通知の設定をします。

App.js
 import { PushNotificationIOS } from 'react-native';
 import PushNotification from 'react-native-push-notification';

 PushNotification.configure({
   // (optional) Called when Token is generated (iOS and Android)
   onRegister(token) {
     console.log('TOKEN:', token);
   },

   // (required) Called when a remote or local notification is opened or received
   onNotification(notification) {
     console.log('NOTIFICATION:', notification);

     // process the notification

     // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
     notification.finish(PushNotificationIOS.FetchResult.NoData);
   },

   // ANDROID ONLY: GCM or FCM Sender ID (product_number) (optional - not required for local notifications, but is need to receive remote push notifications)
   // senderID: 'YOUR GCM (OR FCM) SENDER ID',

   // IOS ONLY (optional): default: all - Permissions to register.
   permissions: {
     alert: true,
     badge: true,
     sound: true,
   },

   // Should the initial notification be popped automatically
   // default: true
   popInitialNotification: true,

   /**
    * (optional) default: true
    * - Specified if permissions (ios) and token (android and ios) will requested or not,
    * - if not, you must call PushNotificationsHandler.requestPermissions() later
    */
   requestPermissions: true,
 });

ローカル通知を利用して、プッシュ通知を表示させます。

App.js
 export default class App extends Component<Props> {
   render() {
     const handleOnPress = () => {
       PushNotification.localNotificationSchedule({
         message: 'これはテストの通知です。アプリ起動後10秒後に配信されます',
         date: new Date(Date.now() + 10 * 1000),
       });
     };

     return (
       <View style={styles.container}>
         <Text>プッシュ通知を表示させるためにボタンを押してください</Text>
         <Button title="クリック" onPress={handleOnPress} />
       </View>
     );
   }
 }

localNotificationScheduleを利用し10秒後に表示させています。
iOSだとアプリを開いた状態だと、通知されません。プッシュ通知を確認するには、アプリを閉じている状態でなければいけません。

  • ボタンをクリック
  • アプリを閉じる
  • 10秒待つ

ことで、上記のコードでプッシュ通知の動作確認をすることができます。

参考

18
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
15