LoginSignup
8
8

More than 5 years have passed since last update.

React Native - Push Notification with Parse (iOS)

Posted at

昨日はReact NativeでParseを使う方法を説明しました。今日はParseでpush通知を実装してみます。

1. Push notificationの設定をする

これはReact Nativeに限った話ではないので、割愛します。
頻繁に参照されているこのドキュメントを参考にしてください。

2. AppDelegate.mに下記を追加

#import "RCTPushNotificationManager.h"
  // Required for the register event.
   - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
   {
    [RCTPushNotificationManager application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
   }
   // Required for the notification event.
   - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification
   {
    [RCTPushNotificationManager application:application didReceiveRemoteNotification:notification];
   }

3. コンポーネント側で登録処理

まず、componentのマウント前に登録のイベントを登録します。

 componentWillMount() {
    PushNotificationIOS.addEventListener('register', this.onRegistration); //
 }

そして、ParseのJS SDK APIを利用して、Parseのデータベースに登録を行います。

  onRegistration(token){
    Parse.registerInstallation({
      "deviceType": "ios",
      "deviceToken": token,
      "channels": ["global"],
    });
  },

4. コンポーネントマウント後にパーミションを要求

パーミションを聞くポップアップを出します。

  componentDidMount(){
    PushNotificationIOS.requestPermissions();
    this.unsubscribe = notificationStore.listen(this.onNotificationUpdated);
  },

5. notificationアップデート用のeventをListen

notifyされた時のイベントをcomponentWillMount()でListenし、その処理を書きます。

 componentWillMount() {
    PushNotificationIOS.addEventListener('register', this.onRegistration);
    PushNotificationIOS.addEventListener('notification', this._onNotification);
 }

バッチをインクリメントして、ここではnotification tableを取ってくる処理をしています。

 _onNotification(notification) {
    //alert("push notification just came!")
    this.setState({
        notifCount: notification.getBadgeCount()
    });
    notificationActions.currentStatus(); //ここではnotificationテーブルを取ってくる処理、アプリによって異なる
  },

6. pushイベント発動の処理を書く

ここではParse CloudCodeに説明しますが、サーバ側のシステムを開発している場合は、Parseの提供するそれぞれのAPIを叩いて、pushさせる処理を書きます。

Cloudcodeの詳細は公式ドキュメントを参照してください。

Parse CouldCodeは、Parse側に簡単な処理を書くことができます。下記は、Parse.Cloud.afterSaveというトリガーを使ってます。Notificaitonテーブルが保存される度に発動します。したがって、モバイルアプリ側でnotification.save()すると, そのデータに応じて、notifyさせることができます。

Parse.Cloud.afterSave("Notification", function(request) {
  Parse.Cloud.useMasterKey();

  var createdAt = request.object.get("createdAt");
  var updatedAt = request.object.get("updatedAt");
  var objectExisted = (createdAt.getTime() != updatedAt.getTime());

  // only if it's created as new object (not update)
  if ( objectExisted ){
    console.log('this is for updating');
  }else{
    var type = request.object.get('type');
    console.log("Type: "+type);
    switch(type){
      case 1:
        askForApproval();
        break;
      default:
        break;
    }
  }
///
function askForApproval(){
...
}

Summary

Push notificationはReact Native標準で入ってますので、特にParseと組み合わせれば比較的容易に実装できるのが分かったと思います。Andoroidには2015年12月時点で標準で無いので、モジュールで対応する必要があります。

明日からはテスト回りについて言及しようかと思います。

8
8
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
8
8