Подтвердить что ты не робот

Swift ios проверяет, включены ли удаленные push-уведомления в ios9 и ios10

Как проверить, разрешили ли пользователю удаленные уведомления на ios 9 или ios 10?

Если пользователь не разрешил или не нажал Нет. Я хочу переключить сообщение с вопросом, хотите ли они включить уведомления.

4b9b3361

Ответ 1

Этот ответ устарел и не поддерживает iOS 10, вы можете проверить этот ответ.


Используйте этот код

let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
     // User is registered for notification
} else {
     // Show alert user is not registered for notification
}

Ответ 2

Apple рекомендует использовать UserNotifications вместо общих экземпляров. Итак, не забудьте импортировать фреймворк UserNotifications. Так как этот фреймворк является новым в iOS 10, использовать этот код на самом деле безопасно только при сборке приложений для iOS10+

let current = UNUserNotificationCenter.current()

current.getNotificationSettings(completionHandler: { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // Notification permission has not been asked yet, go for it!
    } else if settings.authorizationStatus == .denied {
        // Notification permission was previously denied, go to settings & privacy to re-enable
    } else if settings.authorizationStatus == .authorized {
        // Notification permission was already granted
    }
})

Вы можете проверить официальную документацию для получения дополнительной информации: https://developer.apple.com/documentation/usernotifications

Ответ 3

Я попробовал решение Rajat, но это не сработало для меня на iOS 10 (Swift 3). Он всегда говорил, что push-уведомления активированы. Вот как я решил проблему. Это говорит, что "не включен", если пользователь нажал "Не разрешать", или если вы еще не спросили пользователя.

let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
    if notificationType == [] {
        print("notifications are NOT enabled")
    } else {
        print("notifications are enabled")
    }

PS: метод currentUserNotificationSettings устарел в iOS 10.0, но он все еще работает.

Ответ 4

Если ваше приложение поддерживает iOS 10 и iOS 8, используйте код ниже

// At the top, import UserNotifications 
// to use UNUserNotificationCenter
import UserNotifications

Затем,

if #available(iOS 10.0, *) {
    let current = UNUserNotificationCenter.current()
    current.getNotificationSettings(completionHandler: { settings in

        switch settings.authorizationStatus {

        case .notDetermined:
            // Authorization request has not been made yet
        case .denied:
            // User has denied authorization.
            // You could tell them to change this in Settings
        case .authorized:
            // User has given authorization.
        }
    })
 } else {
     // Fallback on earlier versions
     if UIApplication.shared.isRegisteredForRemoteNotifications {
         print("APNS-YES")
     } else {
         print("APNS-NO")
     }
 }

Ответ 5

в iOS11, Swift 4...

 UNUserNotificationCenter.current().getNotificationSettings { (settings) in
        if settings.authorizationStatus == .authorized {
            // Already authorized
        }
        else {
            // Either denied or notDetermined
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                (granted, error) in
                  // add your own 
                UNUserNotificationCenter.current().delegate = self
                let alertController = UIAlertController(title: "Notification Alert", message: "please enable notifications", preferredStyle: .alert)
                let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
                    guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                        })
                    }
                }
                let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
                alertController.addAction(cancelAction)
                alertController.addAction(settingsAction)
                DispatchQueue.main.async {
                    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)

                }
            }
        }
    }

Ответ 6

Здесь решение для получения строки, описывающей текущее разрешение, которое работает с iOS 9 через iOS 11, с Swift 4. Эта реализация использует Когда для обещаний.

import UserNotifications

private static func getNotificationPermissionString() -> Promise<String> {
    let promise = Promise<String>()

    if #available(iOS 10.0, *) {
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.getNotificationSettings { (settings) in
            switch settings.authorizationStatus {
            case .notDetermined: promise.resolve("not_determined")
            case .denied: promise.resolve("denied")
            case .authorized: promise.resolve("authorized")
            }
        }
    } else {
        let status = UIApplication.shared.isRegisteredForRemoteNotifications ? "authorized" : "not_determined"
        promise.resolve(status)
    }

    return promise
}

Ответ 7

@Rajat ответа недостаточно.

  • isRegisteredForRemoteNotifications - это то, что ваше приложение подключилось к APNS и получило токен устройства, это может быть для тихого push-уведомления
  • currentUserNotificationSettings предназначен для разрешений пользователей, без этого в приложение не доставляются оповещения, баннеры или звуковые push-уведомления.

Вот чек

static var isPushNotificationEnabled: Bool {
  guard let settings = UIApplication.shared.currentUserNotificationSettings
    else {
      return false
  }

  return UIApplication.shared.isRegisteredForRemoteNotifications
    && !settings.types.isEmpty
}

Для iOS 10, вместо проверки currentUserNotificationSettings, вы должны использовать UserNotifications

center.getNotificationSettings(completionHandler: { settings in
  switch settings.authorizationStatus {
  case .authorized, .provisional:
    print("authorized")
  case .denied:
    print("denied")
  case .notDetermined:
    print("not determined, ask user for permission now")
  }
})

Push-уведомления могут быть доставлены в наши приложения разными способами, и мы можем попросить об этом

UNUserNotificationCenter.current()
  .requestAuthorization(options: [.alert, .sound, .badge])

Пользователь может зайти в приложение "Настройки" и отключить любое из них в любое время, поэтому лучше всего проверить это в объекте settings

open class UNNotificationSettings : NSObject, NSCopying, NSSecureCoding {


    open var authorizationStatus: UNAuthorizationStatus { get }


    open var soundSetting: UNNotificationSetting { get }

    open var badgeSetting: UNNotificationSetting { get }

    open var alertSetting: UNNotificationSetting { get }


    open var notificationCenterSetting: UNNotificationSetting { get }
}

Ответ 8

class func isRegisteredForRemoteNotifications() -> Bool {
    if #available(iOS 10.0, *) {
        var isRegistered = false
        let semaphore = DispatchSemaphore(value: 0)
        let current = UNUserNotificationCenter.current()
        current.getNotificationSettings(completionHandler: { settings in
            if settings.authorizationStatus != .authorized {
                isRegistered = false
            } else {
                isRegistered = true
            }
            semaphore.signal()
        })
        _ = semaphore.wait(timeout: .now() + 5)
        return isRegistered
    } else {
        return UIApplication.shared.isRegisteredForRemoteNotifications
    }
}

Ответ 9

Даже если пользователь не разрешает push-уведомления, токен устройства доступен. Так что было бы также неплохо проверить, разрешено ли получать push-уведомления.

private func checkPushNotificationAllowed(completionHandler: @escaping (Bool) -> Void) {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            if settings.authorizationStatus == .notDetermined || settings.authorizationStatus == .denied {
                completionHandler(false)
            }
            else {
                completionHandler(true)
            }
        }
    }
    else {
        if let settings = UIApplication.shared.currentUserNotificationSettings {
            if settings.types.isEmpty {
                completionHandler(false)
            }
            else {
                completionHandler(true)
            }
        }
        else {
            completionHandler(false)
        }
    }
}