branch10480’s blog

Topics that I've learned.

【iOS】デバイストークンがPush通知許諾ダイアログで拒否した場合も取得できるかについて

iOSアプリでリモートプッシュを行うもので表示されるこちらのダイアログ。

このダイアログで拒否した場合でもPush通知送信先を表すデバイストークンが取得できるかの検証を行なったのでメモ。

f:id:branch10480:20200803090916p:plain

結論:取得できる!

前提

Push通知許諾ダイアログを出すコード。

center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
   ...
}

デバイストークン登録をするコード。

DispatchQueue.main.async {
    UIApplication.shared.registerForRemoteNotifications()
}

検証用手順

  1. ダイアログを表示
  2. 拒否を選択
  3. デバイストークンが取得できるかを確認

検証に使ったコード

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        // デバイストークンの要求
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

...

// デバイストークンが取得されたら呼び出されるメソッド
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
    // デバイストークン文字列化
    let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined()
    print("デバイストークン取得成功!")
    print(token)
}

結果!

すると。。。取得成功!

「Don't Allow」、「Allow」のどちらを選択してもデバイストークンが取得できる。

※今回はダイアログを出すためにアプリを一度アンインストールしているのでデバイストークンが異なります。

拒否した場合

デバイストークン取得成功!
9cae6402d5f3261a05763079e5ef1b7f9bf9ad329a623c565065bc8a48f800eb

許可した場合

デバイストークン取得成功!
8dfb430ab54de92ddab53e789d1e6c617cb3cfc49b7a1f4f9834685e3ae1afaa

ちなみに、拒否→「設定」アプリから許可の流れをしたときにデバイストークンが変化するのかを調べてみると...

「Don't Allow」選択後

デバイストークン取得成功!
7678fc7e13d9f6792e960365ff7a389ab2b6e5a90653953c25465eee5d58d633

「設定」アプリで許可した後

デバイストークン取得成功!
7678fc7e13d9f6792e960365ff7a389ab2b6e5a90653953c25465eee5d58d633

まとめ

このPush通知の許諾については、再びアプリ内で表示させることはできません。しかし「設定」アプリからは変更ができるのでここをOnにした時にちゃんとPush通知を送れるようにした方が良いですね。

そのためにも、デバイストークン登録は許諾の如何に関わらず取得するようにしましょう。