LoginSignup
109
107

More than 5 years have passed since last update.

[Swift] iOS でプッシュ通知の有効・無効を判定する

Posted at

iOS8 以降とそれ以外で使用する API が異なります。プッシュ通知を許可しているかどうかを判定するメソッドをつくってみました。

class var isPushNotificationEnable: Bool {
        let osVersion = UIDevice.currentDevice().systemVersion
        if osVersion < "8.0" {
            let types = UIApplication.sharedApplication().enabledRemoteNotificationTypes()
            if types == UIRemoteNotificationType.None {
                // push notification disabled
                return false
            }else{
                // push notification enable
                return true
            }
        }else{
            if UIApplication.sharedApplication().isRegisteredForRemoteNotifications() {
                // push notification enable
                return true
            }else{
                // push notification disabled
                return false
            }
        }
    }

おまけ - アプリの設定画面に飛ぶ

プッシュ通知が無効だった場合、ダイアログで"「設定->通知」から有効にしてください" など表示しているアプリがありますが、
使っている側からすると、わざわざホーム画面に戻って設定画面まで行くなんてやらないですよね。

iOS8 からはプログラムで自分のアプリの設定画面に飛べるので、

  1. アプリのプッシュ通知が無効になっているかチェックする
  2. 無効になっていたら「よかったら有効にしてね」という("OK","Cancel"の)ダイアログ表示
  3. ユーザーが "OK" を選択したらアプリの設定画面にプログラムで遷移

がいいとアプローチだと思います。

そのサンプルコードはこちら。

class func openAppSettingPage() -> Void {
        let application = UIApplication.sharedApplication()
        let osVersion = UIDevice.currentDevice().systemVersion
        if osVersion < "8.0" {
            // not supported
        }else{
            let url = NSURL(string:UIApplicationOpenSettingsURLString)!
            UIApplication.sharedApplication().openURL(url)
        }
}

プッシュ通知ができるとユーザーにリーチできる機会が圧倒的に増えるので許可してもらえるような導線になるよう気をつけたいところです。

109
107
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
109
107