最近盛り上がりを見せているハイブリットアプリ開発用フレームワークのReact Native向けSDKを非公式ながら開発中です。今回はついにプッシュ通知に対応しました。まだトークンの受信と通知の受信くらいしか対応していませんが、今後に期待してください。Androidではまだテストしていませんので、今回はiOSでの実装方法です。
使い方
iOSプロジェクトでの対応
React NativeのXcodeプロジェクトを開きます。そして AppDelegate.m
を開きます。そして、下記コードを追加します。これはReact Nativeでプッシュ通知を受け取る際の基本のようです。
// Required to register for notifications - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings]; } // Required for the register event. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } // Required for the notification event. You must call the completion handler after handling the remote notification. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } // Required for the registrationError event. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error]; } // Required for the localNotification event. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [RCTPushNotificationManager didReceiveLocalNotification:notification]; }
さらに node_modules/react-native/Libraries/PushNotificationIOS/RCTPushNotification.xcodeproj
を Xcodeプロジェクトに追加します。
追加したらBuild Phasesの中にあるLink Binary With Librariesの中に libRCTPushNotification.a を追加します。
最後に、CapalitiesでPush NotificationsをONにして完了です。
NCMBの初期化
NCMBの初期化は次のように行います。JavaScript SDKと同じ方式です。
import NCMB from 'react-native-ncmb'; const applicationKey = 'YOUR_APPLICATION_KEY'; const clientKey = 'YOUR_CLIENT_KEY'; const ncmb = new NCMB(applicationKey, clientKey);
デバイストークンの取得
デバイストークンの取得は次のように行います。これだけでデバイストークンの取得とNCMBへの登録が完了します。
ncmb.Installation.setDeviceToken() .then((obj) => { // Get token }, (err) => { console.log(err); });
デバイストークンが欲しい、というだけの場合には getDeviceToken を使います。
ncmb.Installation.getDeviceToken() .then((obj) => { // Get token }, (err) => { console.log(err); });
プッシュ通知の受信
プッシュ通知を受信すると ncmb.Installation.setHandler
が呼び出されます。notification としてJSONオブジェクトが送られてきますので、必要に応じて処理を行います。
ncmb.Installation.setHandler = (notification) => { // Get notification }
まとめ
React Native SDKはまだ認証、データストア、プッシュ通知くらいしか機能がありませんが、今後追加していく予定です。ドキュメントも不足していますので、ぜひフィードバックいただければ嬉しいです。
コードは NCMBMania/react-native-ncmb: Use Nifty mobile backend 's REST API to correspond to React Native にあります。機能要望があればIssueまでお寄せください。オリジナルを開発したsatsuki0221 (yugo)に感謝します!