OutSystems - Mobile

OutSystems Mobile Cordova Apps

アプリケーションのインストルメンテーションを開始する前に、Pyze から App Key を受け取っていることを確認してください。

インストール

モジュールを開きます Extensibility Configurations pyzeプラグインを追加し、インストールして初期化するためのjsonノードを追加します。

{
    "plugin":{
        "identifier":"pyze-outsystems",
        "variables":[{
            "name":"ANDROID_PAK",
            "value":"YOUR_ANDROID_PYZE_APP_KEY"
        },{
            "name":"IOS_PAK",
            "value":"YOUR_IOS_PYZE_APP_KEY"
        }]
    }
}

IOSのプッシュ通知

AppleはApple Push Notification Service(APNS)を提供しており、アプリパブリッシャーがプッシュ通知でユーザーにリーチできるようにしています。

1. P12 証明書の生成

  • apple developerアカウントのCertificates, Identifiers & Profilesページに移動します。
  • 識別子」を選択し、「YOUR_APP_IDENTIFIER」に移動します。
  • 機能」で「プッシュ通知」を選択し、「設定」を選択します。
  • 今すぐ開発/プロダクションSSL証明書の下で、証明書の作成を選択します。
  • ここに記載されているように、証明書署名要求をアップロードします。https://help.apple.com/developer-account/#/devbfa00fef7)
  • 生成された証明書をダウンロードして、Keychain Accessに追加します。
  • ここで、先ほどインポートした証明書を選択し、「エクスポート」を選択します。
  • パスワードを入力し、.p12を任意の場所に保存します。

2. プロバイダとしてPyzeを設定します。

アプリのユーザーに代わってPyzeがプッシュ通知を送信できるようにするには、iOSのプッシュ証明書をPyzeに提供してください。

  • growth.pyze.comにログイン
  • ナビゲーションペインの[設定]をクリックします。
  • ドロップダウンリストから鍵を提供するアプリを選択します。

  • 左メニューのプッシュ通知を選択します。
  • .p12形式のPush通知証明書をアップロードし、p12パスワード(証明書作成時に生成したパスワード)を指定し、プロビジョニングモードを指定します。使用している証明書の種類に応じて、「開発」または「本番」を指定します。

  • 1日と1週間のノルマ制限を選択
  • 保存をクリックします。

3. プッシュ通知を有効にする

  • アプリケーションターゲットの下にあるケイパビリティに移動し、ケイパビリティのPush NotificationsとBackground Modesを追加します。
  • Background Modes]で[Remote notifications]にチェックを入れます。

4. AppDelegateの変更

AppDelegateを以下のように更新します。

@import Pyze;
#import <UserNotifications/UserNotifications.h>

@import CoreMotion;

//Let AppDelegate inherit UNUserNotificationCenterDelegate
@interface ALAppDelegate () <UNUserNotificationCenterDelegate>
@end

@implementation ALAppDelegate

//Initialize Pyze
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [Pyze initialize:@"PYZE_APP_KEY" withLogThrottling: PyzelogLevelMinimal];
    return YES;
}

//Register for remote notification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert +UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {}];
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[PyzeNotification getPyzeDefaultNotificationCategories]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [PyzeNotification initWithLaunchOptions:launchOptions];
    return YES;
}

//Set remote notification token to Pyze
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [Pyze setRemoteNotificationDeviceToken:deviceToken];
}

//Notify Pyze when push received.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    [Pyze processReceivedRemoteNotification:userInfo withState:[[UIApplication sharedApplication] applicationState] withCompletionHandler:completionHandler];
}

//Let pyze handle the remote notification action
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    [PyzeNotification handlePushNotificationResponseWithUserinfo:response.notification.request.content.userInfo actionIdentifier:response.actionIdentifier];
    completionHandler();
}

//Enable app to view notification in foreground
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    completionHandler(UNNotificationPresentationOptionAlert);
}

@end

import Pyze
import UserNotifications

//Let AppDelegate inherit UNUserNotificationCenterDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    //Initialize Pyze
    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        Pyze.initialize("PYZE_APP_KEY", withLogThrottling: .PyzelogLevelMinimal)
        return true
    }

    //Register for remote notification
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self;
        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { granted, error in }
        UNUserNotificationCenter.current().setNotificationCategories(PyzeNotification.getPyzeDefaultNotificationCategories() as! Set<UNNotificationCategory>);
        UIApplication.shared.registerForRemoteNotifications();
        PyzeNotification.initWithLaunchOptions(launchOptions);
        return true
    }

    //Set remote notification token to Pyze
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Pyze.setRemoteNotificationDeviceToken(deviceToken);
    }

    //Notify Pyze when notification received
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        Pyze.processReceivedRemoteNotification(userInfo, with: application.applicationState, withCompletionHandler: completionHandler)
    }

    //Let pyze handle the remote notification action
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        PyzeNotification.handlePushResponse(withUserinfo: response.notification.request.content.userInfo, actionIdentifier: response.actionIdentifier)
        completionHandler()
    }

    //Enable app to view notification in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert);
    }
}

5. アプリのリッチプッシュ通知を有効にする

アプリがプッシュ通知メッセージ内で画像やGIFを受信できるようにします。

  • ファイル] -> [新規作成] -> [ターゲット]に移動し、通知サービス拡張子を作成します。
  • 製品名を入力し、必要な言語を選択します。
  • プロジェクトとしてアプリケーションに埋め込むを選択してください。
  • 上記の拡張機能を追加すると、XCodeはNotificationServiceクラスを作成します。その内容を以下のコードで置き換えてください。

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (NSURL *) attachmentFileURLWithTempLocation:(NSURL *)location name:(NSString *)fileName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray * domainDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [domainDirectories objectAtIndex:0];
    NSString *attachmentLocalFilePath = [documentsDirectory stringByAppendingPathComponent:@"/Pyze/"];
    if(![fileManager fileExistsAtPath:attachmentLocalFilePath]) [fileManager createDirectoryAtPath:attachmentLocalFilePath withIntermediateDirectories:NO attributes:nil error:&error];
    attachmentLocalFilePath =  [attachmentLocalFilePath stringByAppendingFormat:@"/%@",fileName];
    if([fileManager fileExistsAtPath:attachmentLocalFilePath]) {
        [fileManager removeItemAtPath:attachmentLocalFilePath error:&error];
        if (error) NSLog(@"Error in removing file : %@", error.debugDescription);
    }
    [fileManager moveItemAtPath:[location path] toPath:attachmentLocalFilePath error:&error];
    if (error) NSLog(@"Error in moving file to location : %@", error.debugDescription);
    NSURL *mediaFileURL = [NSURL fileURLWithPath:attachmentLocalFilePath];
    return mediaFileURL;
}

- (NSURLSessionDownloadTask *) loadAttachmentsWithURLString:(NSString *)urlString {
    NSURL *mediaURL = [NSURL URLWithString:urlString];
    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:mediaURL completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
          if (!error) {
              NSURL *mediaFileURL = [self attachmentFileURLWithTempLocation:location name:[response suggestedFilename]];
              UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:[response suggestedFilename] URL:mediaFileURL options:nil error:&error];
              if (attachment) self.bestAttemptContent.attachments = @[attachment];
              self.contentHandler(self.bestAttemptContent);
          }
      }];
    return task;
}

#pragma mark - UNNotificationServiceExtension delegate

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    self.bestAttemptContent.title = self.bestAttemptContent.title;
    self.bestAttemptContent.subtitle = self.bestAttemptContent.subtitle;
    NSString *mediaUrlString = request.content.userInfo[@"mediaUrl"];
    NSURLSessionDownloadTask *task = [self loadAttachmentsWithURLString:mediaUrlString];
    [task resume];
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

@end

import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        defer {
            contentHandler(bestAttemptContent ?? request.content)
        }
        guard let attachment = request.attachment else { return }
        bestAttemptContent?.attachments = [attachment]
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

extension UNNotificationRequest {
    var attachment: UNNotificationAttachment? {
        guard let attachmentURL = content.userInfo["mediaUrl"] as? String, let imageData = try? Data(contentsOf: URL(string: attachmentURL)!) else {
            return nil
        }
        return try? UNNotificationAttachment(data: imageData, options: nil)
    }
}

extension UNNotificationAttachment {
    convenience init(data: Data, options: [NSObject: AnyObject]?) throws {
        let fileManager = FileManager.default
        let temporaryFolderName = ProcessInfo.processInfo.globallyUniqueString
        let temporaryFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(temporaryFolderName, isDirectory: true)
        try fileManager.createDirectory(at: temporaryFolderURL, withIntermediateDirectories: true, attributes: nil)
        let imageFileIdentifier = UUID().uuidString + ".jpg"
        let fileURL = temporaryFolderURL.appendingPathComponent(imageFileIdentifier)
        try data.write(to: fileURL)
        try self.init(identifier: imageFileIdentifier, url: fileURL, options: options)
    }
}

プッシュ通知

GoogleはFirebase Cloud Messagingサービス(FCM)を提供し、アプリパブリッシャーがプッシュ通知でユーザーにリーチできるようにしている。

pyzeでFirebaseの資格情報を設定する

Firebaseコンソールにログイン

1.プロジェクトを選択し、プロジェクト名の横にある設定アイコンをクリックします。

2.クラウド メッセージング タブで、レガシー サーバー キーと送信者 ID を検索します。

Pyzeアカウントにログイン

1.設定ページで、ドロップダウンメニューからアプリを選択します。

2.アプリの設定ページで、左側のペインからプッシュ通知の設定に移動します。

3.サーバーキーと送信者IDを入力し、アプリが1日と1週間に送信できるプッシュメッセージの最大数を制限します。

FCM プッシュ通知をアプリプロジェクトに統合する

ルートレベルの build.gradle ファイルに以下のルールを追加し、google-services プラグインを含めるようにします。

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:---Latest-Version---'
    }
}

モジュールのGradleファイル(通常はapp/build.gradle)で、ファイルの一番下にプラグインを適用する行を追加して、Gradleプラグインを有効にします。

apply plugin: 'com.android.application'

android {
    // ...
}

dependencies {
    // ...
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

以下の依存関係をアプリのbuild.gradleファイルに追加します。

dependencies {
    compile "com.google.firebase:firebase-messaging:---Latest-Version---"
}

最新版はいつでもBintrayから入手できます。

Android.Manifestファイルで、Application Tagの間に以下を追加します。

<receiver android:name="com.pyze.android.push.PyzePushTrackingReceiver" android:exported="true"/>
<service
    android:name="com.pyze.android.push.fcm.FcmPushListenerService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

アプリケーションに google-services.json を追加します。

カスタム通知画像

カスタム通知アイコン画像(デフォルトではアプリアイコンが使用されます)を指定するには、pyze_notification_iconとpyze_notification_icon_transperentという名前のプロジェクトのdrawableなフォルダに2つのアイコン画像を配置します。

プッシュ通知処理オプション

Pyze SDK は、基本的なプッシュメッセージとリッチプッシュメッセージの登録と表示をデフォルトで処理します。しかし、表示をカスタマイズしたり、何らかのアクションを実行したい場合など、Push Notificationsの登録を自分で行いたい場合があるかもしれません。

組み込みの表示を使用する

1.プッシュ受信イベントの登録

Pyze.registerForPushNotification(IPyzePushListener listener);

2.プッシュメッセージを受信したら、以下のメソッドを呼び出してメッセージを表示します。

Pyze.showPushNotification(PyzePushMessage pushMessage);

3.使用法

Pyze.registerForPushNotification(new IPyzePushListener() {
    @Override
    public void onPushNotificationReceived(PyzePushMessage pyzePushMessage) {
        //Perform some operation and then ask Pyze to display the notification
        Pyze.showPushNotification(pyzePushMessage);
    }
});

独自のカスタム表示を使用する

1.プッシュ受信イベントの登録

Pyze.registerForPushNotification(IPyzePushListener listener);

2.使用法

Pyze.registerForPushNotification(new IPyzePushListener() {
    @Override
    public void onPushNotificationReceived(PyzePushMessage pyzePushMessage) {
        //Perform internal app operation to your app eg: downloading content in the
        // background.
    }
});

高度な機能

登録を手動で処理するか、FCMのセットアップを自分で実装しているが、Pyzeのプッシュ通知機能を利用したい場合は、以下の方法で設定してください。

登録トークンをPyzeに渡す
@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    ...
    ...
    Pyze.setPushToken(FirebaseInstanceId.getInstance().getToken());
}

受信したプッシュメッセージがPyzeからのものであれば、プッシュメッセージを渡して以下のメソッドを呼び出します。で述べたように自分で処理するか、以下のようにPyzeに処理を任せることができます。

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    if(remoteMessage.getData().get("pnty").equals("pyze")){
        PyzePushMessage message = new PyzePushMessage(remoteMessage.getData());
        //Handle displaying push notification manually or through Pyze
        Pyze.showPushNotification(message);
    }
}

アプリ内通知

アプリ内通知は、アプリを使用しているユーザーがアプリを使用した際に、アプリビジネスがユーザーに連絡を取ることを可能にします。アプリ内通知はpyze sdkに組み込まれており、追加の依存関係はありません。企業はDynamic FunnelsやIntelligence Explorerから手動で、Growth Automationからワークフローやキャンペーンに基づいて自動的にユーザーに連絡することができます。アプリ内通知は、新しいメッセージをチェックし、通知でモーダルをポップアップさせたい場所はどこでも、次のmethedを呼び出すCampaignsから送信することができます。

showInAppNotification(callback);