Swift ios는 ios9 및 ios10에서 원격 푸시 알림이 활성화되어 있는지 확인합니다.
사용자가 ios 9 또는 ios 10에서 원격 알림을 활성화했는지 확인하려면 어떻게 해야 합니까?
사용자가 허용하지 않거나 아니요를 클릭한 경우 알림을 활성화할지 묻는 메시지를 전환합니다.
은 애플 에서합니다를 할 것을 합니다.UserNotifications
공유 인스턴스 대신 프레임워크를 선택합니다.요를 .UserNotifications
틀을 짜다 이 프레임워크는 에서 새로운 에 iOS 10+ 이 프레임워크는 iOS 10+ 용 앱 구축에 이 코드를 사용하는 것이 정말 안전합니다용 앱 이은 정말합니다.
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 에서 확인하실 수 있습니다.
10을 한 후 된 입니다.UNUserNotificationCenter
.
먼저 당신은 해야합니다.import UserNotifications
그리고나서
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { permission in
switch permission.authorizationStatus {
case .authorized:
print("User granted permission for notification")
case .denied:
print("User denied notification permission")
case .notDetermined:
print("Notification permission haven't been asked yet")
case .provisional:
// @available(iOS 12.0, *)
print("The application is authorized to post non-interruptive user notifications.")
case .ephemeral:
// @available(iOS 14.0, *)
print("The application is temporarily authorized to post notifications. Only available to app clips.")
@unknown default:
print("Unknow Status")
}
})
이 코드는 iOS 9까지 작동합니다. iOS 10은 위의 코드 스니펫을 사용합니다.
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
// User is registered for notification
} else {
// Show alert user is not registered for notification
}
Rajat의 솔루션을 사용해 보았지만 iOS 10(Swift 3)에서는 작동하지 않았습니다.푸시 알림이 활성화되어 있다고 항상 말합니다.아래는 제가 문제를 해결한 방법입니다.사용자가 "허용 안 함"을 누르거나 아직 사용자에게 묻지 않은 경우 "사용 가능하지 않음"이라고 표시됩니다.
let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
if notificationType == [] {
print("notifications are NOT enabled")
} else {
print("notifications are enabled")
}
PS: currentUserNotificationSettings
에서 더 사용되지 않지만 OS 10.0에서 더 이상 사용되지 않지만 여전히 작동 중입니다.
만약 당신의 앱이 iOS 10과 iOS 8을 지원한다면 9는 아래의 코드를 사용합니다.
// 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")
}
}
iOS11, 스위프트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)
}
}
}
}
@Rajat의 대답으로는 부족합니다.
isRegisteredForRemoteNotifications
푸시 알림다 APNS이를 일 수 .currentUserNotificationSettings
는 이 으로,고,다에 또는
여기 수표가 있습니다.
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")
}
})
푸시 알림은 여러 가지 방법으로 우리의 앱에 전달될 수 있으며, 우리는 그것을 요청할 수 있습니다.
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 }
}
iOS12와 Swift4도 iOS13과 Swift5를 지원합니다. 여기서 확인하실 수 있는 git도 만들었습니다.
이 싱글톤 파일을 XCode Project에 추가하기만 하면 됩니다.
import Foundation
import UserNotifications
import UIKit
class NotificaionStatusCheck {
var window: UIWindow?
private var currentViewController : UIViewController? = nil
static let shared = NotificaionStatusCheck()
public func currentViewController(_ vc: UIViewController?) {
self.currentViewController = vc
checkNotificationsAuthorizationStatus()
}
private func checkNotificationsAuthorizationStatus() {
let userNotificationCenter = UNUserNotificationCenter.current()
userNotificationCenter.getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .authorized:
print("The app is authorized to schedule or receive notifications.")
case .denied:
print("The app isn't authorized to schedule or receive notifications.")
self.NotificationPopup()
case .notDetermined:
print("The user hasn't yet made a choice about whether the app is allowed to schedule notifications.")
self.NotificationPopup()
case .provisional:
print("The application is provisionally authorized to post noninterruptive user notifications.")
self.NotificationPopup()
}
}
}
private func NotificationPopup(){
let alertController = UIAlertController(title: "Notification Alert", message: "Please Turn on the Notification to get update every time the Show Starts", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) 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.currentViewController?.present(alertController, animated: true, completion: nil)
}
}
}
ViewController에서 이 코드에 액세스하려면 viewDidLoad에서 이 코드를 사용합니다.
NotificaionStatusCheck.shared.currentViewController(self)
여기 iOS 9에서 작동하는 현재의 권한을 설명하는 문자열을 얻기 위한 해결책이 있습니다. iOS 11과 Swift 4에서 작동합니다.이 구현에서는 약속에 When을 사용합니다.
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
}
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
}
}
사용자가 푸시 알림을 허용하지 않더라도 장치 토큰을 사용할 수 있습니다.그래서 푸시 알림을 받아도 되는지 확인해 보는 것도 좋을 것 같습니다.
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)
}
}
}
위의 모든 답변은 거의 정확하지만 푸시 알림이 활성화되어 있고 모든 옵션(경보 설정, 잠금 화면 설정 등)이 비활성화되어 있는 경우,authorizationStatus
될 것이다authorized
푸시 알림을 받지 못할 겁니다
사용자가 원격 알림을 받을 수 있는지 확인하는 가장 적절한 방법은 이러한 모든 설정 값을 확인하는 것입니다.확장 기능을 사용하면 달성할 수 있습니다.
참고: 이 솔루션은 iOS 10+에 적합합니다.이전 버전을 지원하는 경우 이전 답변을 읽어보십시오.
extension UNNotificationSettings {
func isAuthorized() -> Bool {
guard authorizationStatus == .authorized else {
return false
}
return alertSetting == .enabled ||
soundSetting == .enabled ||
badgeSetting == .enabled ||
notificationCenterSetting == .enabled ||
lockScreenSetting == .enabled
}
}
extension UNUserNotificationCenter {
func checkPushNotificationStatus(onAuthorized: @escaping () -> Void, onDenied: @escaping () -> Void) {
getNotificationSettings { settings in
DispatchQueue.main.async {
guard settings.isAuthorized() {
onDenied()
return
}
onAuthorized()
}
}
}
}
비동기가 있는 새로운 스타일
static func getPermissionState() async throws {
let current = UNUserNotificationCenter.current()
let result = await current.notificationSettings()
switch result.authorizationStatus {
case .notDetermined:
//
case .denied:
//
case .authorized:
//
case .provisional:
//
case .ephemeral:
//
@unknown default:
//
}
}
언급URL : https://stackoverflow.com/questions/40531103/swift-ios-check-if-remote-push-notifications-are-enabled-in-ios9-and-ios10
'programing' 카테고리의 다른 글
Mysql, 긴/큰 데이터에서 넓은 데이터로 재구성 (0) | 2023.10.14 |
---|---|
JS 파일 내 PHP 상수 (0) | 2023.10.14 |
WooCommerce는 가격이 아닌 날짜로만 주문하는 것 같습니다. (0) | 2023.10.14 |
MySQL Server가 사라졌습니다(MariaDB - MEMORY Engine) (0) | 2023.10.14 |
클릭할 때 수신기 제거 (0) | 2023.10.14 |