LoginSignup
6
2

More than 3 years have passed since last update.

NWPusherで手軽にiPhone実機へプッシュ通知を送り、テストをする

Posted at

iPhoneアプリのデバッグ過程でプッシュ通知をテスト端末に送る必要があったのですが、
NWPusherのおかげで手軽に何度もプッシュ通知を送ることができ、とても捗りました!

NWPusherをインストールする

GitHubのページは以下です。
GitHub - noodlewerk/NWPusher: OS X and iOS application and framework to play with the Apple Push Notification service (APNs)

Readmeに記載されていますが、Homebrew caskでのインストールがオススメです。

brew cask install pusher

Homeberwを使わない場合は最新のバイナリーがダウンロードできます。
Latest Release · noodlewerk/NWPusher · GitHub

インストールできたら、NWPusher(以下Pusher)を起動します。

p12ファイルのインポート

p12ファイルが手元にない場合は、作成するか、権限のある人に依頼しましょう!
【iOS】複雑な証明書周りをあっさり整理してみた – ゆるtech。

p12ファイルを入手できたら、
PusherアプリのImport PKCS #12 file (.p12)...からインポートします。

デバイストークンの入手

プッシュ通知の送り先を識別するための端末個別のトークンが必要なので、下記のオーバーライドメソッドで取得します。
8桁×8の英数字文字列がコンソールに出力されるのでコピーしましょう。

Swift

AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // ① プッシュ通知利用許可のリクエスト
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        guard granted else { return }

        DispatchQueue.main.async {
            // ② プッシュ通知利用の登録
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
    return true
}

// ③ プッシュ通知の利用登録が成功した場合(引数でデバイストークンが取れる)
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("Device token: \(deviceToken)")
}

// ④ (省略可)プッシュ通知の利用登録が失敗した場合はこちらが呼ばれる
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register to APNs: \(error)")
}

Objective-C

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ① プッシュ通知利用許可のリクエスト
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // ② プッシュ通知利用の登録
                [UIApplication.sharedApplication registerForRemoteNotifications];
            });
        }
    }];
    return YES;
}

// ③ プッシュ通知の利用登録が成功した場合(引数でデバイストークンが取れる)
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"Device token: %@", deviceToken);
}

// ④ (省略可)プッシュ通知の利用登録が失敗した場合はこちらが呼ばれる
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"Failed to register to APNs: %@", error);
}

デバイストークンの入力

コピーしたデバイストークン(8桁×8の英数字文字列)をPusherアプリに入力します。
8桁ごとにスペースで区切られたままでも大丈夫です。

  • Expiry(有効期限)
  • Priority(優先度)

を設定することもできますが、デフォルトのNoneでも問題ありません。

書かなかったこと

以下のことは試していないです。
GitHubのReadmeに詳しくHow-toが書いてありました。

  • CocoaPodsまたはCarthageを用いて、iPhoneアプリにフレームワークを入れればiPhoneからプッシュ通知を送ることができる。
  • iOS, macOS で、プログラムを書いて通知を送信するためのフレームワークとしても使用できる。

参考リンク

iOS13におけるプッシュ通知に必要なデバイストークンの取得方法 - Takahiro Octopress Blog

6
2
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
6
2