Pendoでリッチプッシュ通知を送信する(Androidの場合)
リッチプッシュ通知ガイドを有効にするには、以下の手順に従ってください。
アプリでプッシュ通知を受信できることが確認できたら、PendoのSDKに特有の2つのステップを完了する必要があります。まず、Pendoがアプリにプッシュ通知を送信できるように、サーバーキーを提供する必要があります。
サーバーキーを提供するには、Pendo管理者ページに移動して、リストの中の自分のアプリをクリックします。次に、上部のメニューにある[アプリの詳細(App Details)]リンクをクリックします。[プッシュ設定(Push Settings)]という項目が表示されます。編集アイコンをクリックして、APIキーと、オプションでアプリ内のアイコン画像とサウンドファイルの名前を設定します。
次に、アプリに少量のコードを追加する必要があります。手順は、Firebase Cloud Messagingを使用しているかどうかによって異なります。
Firebaseの手順
以下のGoogleの説明を参考にして、Firebaseの設定を行ってください。Googleはサンプルも提供しています。
ステップ1:メインアクティビティでonCreate()メソッドに以下のコードを追加します。
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(newOnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()){
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
Insert.setPushId(token);
}
});
ステップ2:FirebaseMessagingServiceクラスを作成します。
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import sdk.insert.io.Insert;
import sdk.insert.io.InsertPushHandler;
public class MyMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (Insert.isInsertPush(remoteMessage.getData())){
InsertPushHandler.handleInsertPush(remoteMessage.getData());
}
}
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(newOnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()){
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
Insert.setPushId(token);
}
});
}
}
Firebaseは新しいトークンが生成されるたびにこのサービスが開始されることを認識しているので、追加の作業は必要ありません。
ステップ3:Androidマニフェストをタグの下に追加します。
<service android:name=".MyMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
リッチプッシュ通知(iOSの場合)
以下の手順で、Pendoを使ってアプリでプッシュ通知を送受信します。Pendoで適切な設定手順を行う前に、iOSアプリがプッシュ通知用に正しく設定されていることを確認してください。iOSにプッシュ通知を実装する方法については、優れた記事が多数あります。また、Appleのドキュメントも参考にすることができます。アプリでプッシュ通知を受信できることが確認できたら、Pendoに特有の2つのステップを完了する必要があります。まず、Pendoがアプリにプッシュ通知を送信できるように、P12形式のAPNS証明書を提供する必要があります。P12証明書を提供するには、[サブスクリプション設定(Subscription Settings)]ページ(https://app.pendo.io/admin )に移動し、リストの中から自分のアプリをクリックします。次に、上部のメニューにある[アプリの詳細(App Details)]リンクをクリックします。[プッシュ設定(Push Settings)]という項目が表示されます。編集アイコンをクリックして、適切なP12証明書をアップロードし、証明書の作成時に使用したパスワードを指定します。
なお、Pendoのプッシュ通知を利用するには、開発(Development)または本番(Production)のどちらかの証明書をアップロードする必要があります。両方をアップロードすることも可能です。有効なP12証明書を用意したら、アプリのソースに2行のコードを追加する必要があります。
次に、アプリのソースに2行のコードを追加する必要があります。プッシュ通知を受信するためにプッシュ登録を行うときは、プッシュ通知トークンをPendoサービスに渡す必要があります。これを行うには、AppDelegateのapplication:didRegisterForRemoteNotificationsWithDeviceToken:関数で、InsertManagerインスタンスにpushIdプロパティを設定します。
(Objective-C):
“`C++ [InsertManager sharedManager].pushId=
Swift:
```Swift InsertManager.sharedManager().pushId= <device token>
通知の転送
アプリがプッシュ通知を受信したら、通知オブジェクトをPendoに渡す必要があります。そのためには、AppDelegateクラスのapplication:didReceiveRemoteNotification:関数に以下のコードを追加します。
(Objective-C):
“`C++ [[InsertManager sharedManager] didReceiveRemoteNotification:userInfo];
Swift:
```Swift InsertManager.sharedManager().didReceiveRemoteNotification(userInfo:userInfo)
通知拡張機能の作成
通知の拡張機能により、開発者はプッシュ通知がユーザーに配信される前にそれをインターセプトする仕組みを使用できます。これにより、プッシュ通知に含まれるメディアの管理など、ペイロードデータの特別な処理が可能になります。以下の例では、ガイド定義の一部として提供された画像を抽出し、通知の一部として表示する通知拡張機能を作成しています。
- [Xcode]メニューで、[ファイル(File)]、[新規(New)]、[ターゲット(Target)]の順に移動し、[通知サービスの拡張(Notification Service Extension)]を選択します。
- 拡張機能に名前をつけます。新しいコードが
UNNotificationServiceExtension
を継承していることを確認します。 - 自分の実装でコードを上書きしてください。以下はその一例です。
- 拡張機能「iOS Target Deploy」を使用する場合は、デバイスのバージョンが対象デバイスよりも低い必要があります。
overide func didReceiveの例:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
if let attachmentString = bestAttemptContent.userInfo["image_url"] as? String,
let attachmnetUrl = URL(string: attachmentString) {
print("attachmentString \(attachmentString)")
print("attachmnetUrl \(attachmnetUrl)")
let session = URLSession(configuration: URLSessionConfiguration.default)
let downloadTask = session.downloadTask(with: attachmnetUrl, completionHandler: {(url, _, error) in
if let error = error {
print("Error downloading attachment: \(error.localizedDescription)")
} else if let url = url {
let attachment = try! UNNotificationAttachment(identifier: attachmentString, url: url, options: [UNNotificationAttachmentOptionsTypeHintKey : kUTTypeJPEG])
bestAttemptContent.attachments = [attachment]
}
contentHandler(bestAttemptContent)
})
downloadTask.resume()
}
}
}
Cordovaを使ったプッシュ通知
- 新しいCordovaプロジェクトを作成するか、既存のプロジェクトを使用します。
- 以下の説明に従って、Pendoプラグインを追加します。
- 以下のコマンドラインでプッシュ通知のCordovaプラグインを追加します。
cordova plugin add phonegap-plugin-push --variable SENDER_ID=<sender-id>
javascriptファイルの「DeviceReady」の後に以下のコードを追加してください。
var push = PushNotification.init({"android": {"senderID": "<sender-id>"}, "ios": {"alert": "true", "badge": "true", "sound": "true"}, "windows": {} } ); push.on('registration',function(data) { window.plugins.Insert.setPushId(data.registrationId); }); push.on('notification',function(data) { // this function will be called when the push notification is received by the app }); push.on('error',function(e) { console.log(e.message); });