プッシュ通知 (Cocos2d-x)¶
プッシュ通知の設定¶
APNs証明書の設定 (iOS) と FCMの設定 (Android) を参照し、設定してください。
Firebase C++ SDKを導入する¶
Firebaseの公式ドキュメント を参照し、 libfirebase_app.a と libfirebase_messaging.a を導入してください。なお、Firebase C++ SDKはAndroidアプリで利用するものであり、iOSアプリでは利用しません。
iOSプロジェクトの実装¶
APNsへの端末の登録¶
プッシュ通知を受信するために、アプリ起動時にAPNsへの端末登録処理を実装します。
Target > Build Pahses > Link Binary With Libraries から UserNotifications.framework を追加します。
次に AppController.mm
に下記のコードを追加してください。
// AppController.mm
#import <Repro/Repro.h>
#import <UserNotifications/UserNotifications.h>
// Conforms AppController class to UNUserNotificationCenterDelegate protocol
@interface AppController() <UNUserNotificationCenterDelegate>
@end
@implementation AppController
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_9_x_Max) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
return YES;
}
デバイストークンをReproに送信¶
プッシュ通知の宛先を指定するためにデバイストークンをReproに送信します。
デバイストークンの取得に成功した場合は application:didRegisterForRemoteNotificationsWithDeviceToken:
メソッドが呼び出されるので、その中でReproにデバイストークンを渡します。
デバイストークンの取得に失敗した場合は application:didFailToRegisterForRemoteNotificationsWithError:
メソッドが呼び出されるので、エラーの内容を見て適宜対処します。
// AppController.mm
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[Repro setPushDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"Remote Notification Error: %@", error);
}
Androidプロジェクトの実装¶
AndroidManifest.xml
ファイルを編集する¶
Receiverの登録¶
以下のXML中の "YOUR_PACKAGE_NAME" をアプリケーションのパッケージ名に置き換え、AndroidManifest.xmlの <application>
タグの中に追加してください。
<receiver
android:name="io.repro.android.ReproReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="YOUR_PACKAGE_NAME" />
</intent-filter>
</receiver>
通知チャンネルの設定¶
Android Oにて、ユーザーが通知を管理できるように通知チャンネルが導入されました。
Repro SDKで利用する通知チャンネルの設定を行うには、「ID」「名前」「ユーザー向けの説明」「badgeの表示有無」を指定する必要があります。
以下のXML中の value
, resource
を設定したい値に書き換え、AndroidManifest.xmlの <application>
タグの中に追加してください。
IDと名前の指定は必須、その他は省略可能です。「ユーザー向けの説明」省略時は空文字列、「badgeの表示有無」省略時はbadgeの表示有りとなります。
警告
- アプリのtargetSDKVersionが26以上かつAndroid O以降の機種で動作させる場合、IDと名前が指定されていなければSDKはReproからのプッシュ通知を表示いたしませんのでご注意ください。
ChannelId
に指定する値は、整数や小数ではなくtest ID
のような文字列を指定してください。文字列以外の値を指定するとチャンネルIDの指定がうまく動作せず、プッシュ通知が表示されません。ChannelName
とChannelDescription
の設定はandroid:resource
属性を使用してください。
<meta-data
android:name="io.repro.android.PushNotification.ChannelId"
android:value="YOUR_CHANNEL_ID">
</meta-data>
<meta-data
android:name="io.repro.android.PushNotification.ChannelName"
android:resource="@string/YOUR_CHANNEL_NAME">
</meta-data>
<meta-data
android:name="io.repro.android.PushNotification.ChannelDescription"
android:resource="@string/YOUR_CHANNEL_DESCRIPTION">
</meta-data>
<meta-data
android:name="io.repro.android.PushNotification.ShowBadge"
android:value="true">
</meta-data>
指定されたIDの通知チャンネルが存在しない場合はAndroidManifest.xmlの指定を基にSDKが自動で作成し、指定されたIDの通知チャンネルが存在する場合は既存のものを利用します。
既存のものを利用する場合、SDKは「名前」、「ユーザー向けの説明」及び「チャンネルの重要度」を更新します。
また、アプリのtargetSDKVersionが25以下の場合、あるいは、Android O未満の機種の場合は、SDKは上記の通知チャンネルに関する設定を無視します。
注釈
通知チャンネルはAndroid Oで導入されたAndroidの標準機能です。通知チャンネルの詳細は こちら をご覧ください。
アイコンと背景色のカスタマイズ¶
Android5.0以降の機種で、通知エリアに表示されるアイコンとその背景色をカスタマイズする場合は、以下のXMLをAndroidManifest.xmlの <application>
タグの中に追加してください。Android5.0未満の機種では以下の設定は無視され、通知エリアにはアプリケーションのアイコンおよびシステムデフォルトの背景色が使用されます。
<meta-data
android:name="io.repro.android.PushNotification.SmallIcon"
android:resource="@drawable/YOUR_ICON_ID">
</meta-data>
<meta-data
android:name="io.repro.android.PushNotification.AccentColor"
android:resource="@color/YOUR_COLOR_ID">
</meta-data>
Registration IDをReproに送信¶
AppActivity
の onCreate(Bundle savedInstanceState)
内にて enablePushNotification()
を呼び出します。
// AppActivity.java
package org.cocos2dx.cpp;
import android.os.Bundle;
import org.cocos2dx.lib.Cocos2dxActivity;
import io.repro.android.Repro;
public class AppActivity extends Cocos2dxActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Repro.enablePushNotification();
}
}
次に、firebase::messaging::Listener
interfaceを実装したクラスの OnTokenReceived メソッドにて、ReproCpp::setPushRegistrationID
を呼び出してください。
#include "ReproCpp.h"
...
class MyFirebaseMessagingListener : public firebase::messaging::Listener {
...
public:
void OnTokenReceived(const char* token) override {
ReproCpp::setPushRegistrationID(token);
}
上記の実装が終わったら、 プッシュ通知作成画面 をご覧ください。
プッシュ通知受信時の動作をカスタマイズする¶
Repro Cocos2d-x SDKは オプション:プッシュ通知受信時の動作をカスタマイズする に示すプッシュ通知受信時の動作のカスタマイズには対応しておりません。ご了承ください。
オプション:ユニバーサルリンク/アプリリンクを使用する¶
端末に表示されたプッシュ通知およびアプリ内メッセージに設定されたリンクをタップした際に実行されるURLには、ユニバーサルリンク(またはアプリリンクと呼ばれる)を指定することが可能です。 (簡単のため、以下ではこれらをユニバーサルリンクと呼びます)
アプリにてユニバーサルリンクの実行時の処理を追加するには、以下の通り実装を行う必要があります。 (ここで設定された動作は、プッシュ通知およびアプリ内メッセージ対し有効となります。)
ユニバーサルリンクのURLパターンを登録する¶
ユニバーサルリンクを利用するためには、まずユニバーサルリンクのURLのパターン(正規表現)を指定する必要があります。
この指定は、iOSの場合は AppDelegate
または .plist
ファイル、Androidの場合は Application
継承クラス または AndroidManifest.xml
ファイルのどちらか一方に記述することで行うことができます。
// AppDelegate.m
#import <Repro/Repro.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[Repro addOpenUrlFilterRegEx:@"https://example\\.com/page/"];
[Repro addOpenUrlFilterRegEx:@"your-domain\\.com/.+\?universal=true"];
...
}
// .plist file
/*
<dict>
<key>RPROpenUrlFilterRegExList</key>
<array>
<string>https://example\.com/page/</string>
<string>your-domain\.com/.+\?universal=true</string>
</array>
...
</dict>
*/
// MyApplication.java
import io.repro.android.Repro;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Repro.addOpenUrlFilterRegEx("https://example\\.com/page/");
Repro.addOpenUrlFilterRegEx("your-domain\\.com/.+\\?universal=true");
...
}
...
}
// AndroidManifest.xml
// To specify multiple URL patterns, enter them separated by commas.
<application>
...
<meta-data
android:name="io.repro.android.OpenUrlFilterRegExList"
android:value="https://example\\.com/page/;your-domain\\.com/.+\\?universal=true">
</meta-data>
</application>
// AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{
Repro.add(openUrlFilterRegEx: "https://example\\.com/page/")
Repro.add(openUrlFilterRegEx: "your-domain\\.com/.+\\?universal=true")
...
}
// .plist file
/*
<dict>
<key>RPROpenUrlFilterRegExList</key>
<array>
<string>https://example\.com/page/</string>
<string>your-domain\.com/.+\?universal=true</string>
</array>
...
</dict>
*/
Please follow native iOS and Android instructions in order to add the filters
to the plist/AndroidManifest files or the main AppDelegate/Application classes.
Please follow native iOS and Android instructions in order to add the filters
to the plist/AndroidManifest files or the main AppDelegate/Application classes.
// YourAppNameScene.cpp
bool YourAppName::init() {
ReproCpp::addOpenUrlFilterRegEx("https://example\\.com/page/");
ReproCpp::addOpenUrlFilterRegEx("your-domain\\.com/.+\\?universal=true");
...
}
Please follow native iOS and Android instructions in order to add the filters
to the plist/AndroidManifest files or the main AppDelegate/Application classes.
Please follow native iOS and Android instructions in order to add the filters
to the plist/AndroidManifest files or the main AppDelegate/Application classes.
ユニバーサルリンク実行時の処理を登録する¶
次に、ユニバーサルリンクが実行された際に動作するコールバック処理を実装します。 処理内には、例えばURLのパターンに応じて画面遷移を行う動作などを記述します。
#import <Repro/Repro.h>
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[Repro setOpenUrlCallback:^(NSURL *url) {
if ([url.host isEqualToString:@"example.com"]) {
// In case of your universal link perform navigation, present content, ...
handleUniversalLink(url);
}
}];
...
[Repro setup:@"YOUR_APP_TOKEN"];
...
}
// Set a callback that is executed everytime an URL is about to be opened
Repro.setOpenUrlCallback { url in
if url.host == "example.com" {
// In case of your universal link perform navigation, present content, ...
handleUniversalLink(url)
}
}
...
Repro.setup(token: "YOUR_APP_TOKEN")
...
import io.repro.android.Repro;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// In order to execute a callback when a push notification is tapped,
// the callback must be set in Application, not Activity.
Repro.setOpenUrlCallback(new Repro.OpenUrlCallback() {
// ** This callback method is executed in the main thread **
@Override
public void onOpened(Uri uri) {
if ("example.com".equals(uri.getHost())) {
// In case of your universal link perform navigation, present content, ...
}
}
});
...
Repro.setup(this, YOUR_APP_TOKEN);
...
}
...
}
Repro.setOpenUrlCallback((uri) { // uri is of type Uri
debugPrint("Universal Link Callback Handler received: " + uri.toString());
});
// Somewhere before Repro.Setup(...)
Repro.SetOpenUrlCallback(uri => // uri is of type Uri
{
Debug.Log("Universal Link Callback Handler received: " + uri.ToString());
});
bool YourAppName::init() {
ReproCpp::addOpenUrlFilterRegEx(...);
ReproCpp::setOpenUrlCallback([](const char *url) {
if (strcmp(url, "example.com") == 0) {
// In case of your universal link perform navigation, present content, ...
}
});
ReproCpp::setup("YOUR_APP_TOKEN")
...
}
Repro.setOpenUrlCallback(function(url) { // url is of type String
alert('Universal Link Callback Handler received: ' + url);
if (url.includes("http://example.org")) {
// In case of your universal link perform navigation, present content, ...
}
});
Repro.setOpenUrlCallback( (url) => { // url is of type String
console.log('Universal Link Callback Handler received: ' + url);
if (url.includes("http://example.org")) {
// In case of your universal link perform navigation, present content, ...
}
});
ブリッジ処理を実装する¶
最後に、コールバックの実行に必要なブリッジ処理を実装します。 実装方法の詳細は ブリッジクラスの追加 を参照してください。