Ich suche nach einer Möglichkeit, festzustellen, ob der Benutzer seine Push-Benachrichtigungen für meine Anwendung über Einstellungen aktiviert oder deaktiviert hat.
Rufen Sie enabledRemoteNotificationsTypes
auf und überprüfen Sie die Maske.
Zum Beispiel:
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone)
// blah blah blah
iOS8 und höher:
[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]
Ich kann nicht kommentieren (nicht genug Reputation), aber es geht um: Quantumpotatos Ausgabe:
Wo types
gegeben ist durch
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
man kann verwenden
if (types & UIRemoteNotificationTypeAlert)
anstatt
if (types == UIRemoteNotificationTypeNone)
können Sie nur prüfen, ob Benachrichtigungen aktiviert sind (und sich nicht um Geräusche, Abzeichen, Benachrichtigungscenter usw. kümmern). Die erste Codezeile (types & UIRemoteNotificationTypeAlert
) gibt YES
zurück, wenn "Alert Style" auf "Banners" oder "Alerts" gesetzt ist, und NO
, wenn "Alert Style" unabhängig von anderen Einstellungen auf "None" gesetzt ist.
In der neuesten Version von iOS ist diese Methode nun veraltet. Um sowohl iOS 7 als auch iOS 8 zu unterstützen, verwenden Sie:
UIApplication *application = [UIApplication sharedApplication];
BOOL enabled;
// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
enabled = [application isRegisteredForRemoteNotifications];
}
else
{
UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
enabled = types & UIRemoteNotificationTypeAlert;
}
Aktualisierter Code für Swift4.0, iOS11
import UserNotifications
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
//Not authorised
UIApplication.shared.registerForRemoteNotifications()
}
Code für Swift3.0, iOS10
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
// User is registered for notification
} else {
// Show alert user is not registered for notification
}
Ab iOS9 ist Swift 2.0 UIRemoteNotificationType veraltet. Verwenden Sie folgenden Code
let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
if notificationType == UIUserNotificationType.none {
// Push notifications are disabled in setting by user.
}else{
// Push notifications are enabled in setting by user.
}
prüfen Sie einfach, ob Push-Benachrichtigungen aktiviert sind
if notificationType == UIUserNotificationType.badge {
// the application may badge its icon upon a notification being received
}
if notificationType == UIUserNotificationType.sound {
// the application may play a sound upon a notification being received
}
if notificationType == UIUserNotificationType.alert {
// the application may display an alert upon a notification being received
}
Nachfolgend finden Sie ein vollständiges Beispiel für iOS8 und iOS7 (und niedrigere Versionen). Beachten Sie, dass Sie vor iOS8 nicht zwischen "Remote-Benachrichtigungen deaktiviert" und "Nur In Sperrbildschirm anzeigen aktiviert" unterscheiden können.
BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// iOS8+
remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;
UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;
noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;
} else {
// iOS7 and below
UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;
noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}
NSLog(@"Notification type status:");
NSLog(@" None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@" Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@" Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@" Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");
Swift 3+
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
// settings.authorizationStatus == .authorized
})
} else {
return UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false
}
RxSwift Observable Version für iOS10 +:
import UserNotifications
extension UNUserNotificationCenter {
static var isAuthorized: Observable<Bool> {
return Observable.create { observer in
DispatchQueue.main.async {
current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
if settings.authorizationStatus == .authorized {
observer.onNext(true)
observer.onCompleted()
} else {
current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
observer.onNext(granted)
observer.onCompleted()
}
}
})
}
return Disposables.create()
}
}
}
Beim Versuch, sowohl iOS8 als auch niedriger zu unterstützen, hatte ich nicht viel Glück, isRegisteredForRemoteNotifications
zu verwenden, wie Kevin vorgeschlagen hatte. Stattdessen habe ich currentUserNotificationSettings
verwendet, was in meinen Tests hervorragend funktioniert hat.
+ (BOOL)notificationServicesEnabled {
BOOL isEnabled = NO;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){
UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
isEnabled = NO;
} else {
isEnabled = YES;
}
} else {
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert) {
isEnabled = YES;
} else{
isEnabled = NO;
}
}
return isEnabled;
}
Leider hat keine dieser Lösungen wirklich das Problem gelöst, da die APIs am Ende des Tages ernsthaft fehlen, wenn es um die Bereitstellung der relevanten Informationen geht. Sie können ein paar Vermutungen anstellen, jedoch ist die Verwendung von currentUserNotificationSettings
(iOS8 +) in der aktuellen Form nicht ausreichend, um die Frage wirklich zu beantworten. Obwohl viele der Lösungen hier zu vermuten scheinen, dass entweder das oder isRegisteredForRemoteNotifications
eher eine endgültige Antwort ist, ist sie es wirklich nicht.
Bedenken Sie:
mit isRegisteredForRemoteNotifications
Dokumentation heißt es:
Gibt JA zurück, wenn die Anwendung derzeit für Remote-Benachrichtigungen registriert ist, wobei systemweite Einstellungen berücksichtigt werden.
Wenn Sie jedoch einfach eine NSLog
in Ihren App-Delegierten werfen, um das Verhalten zu beobachten, ist es offensichtlich, dass sich dies nicht so verhält, wie wir es erwarten. Es bezieht sich tatsächlich direkt auf Remote-Benachrichtigungen, die für diese App/dieses Gerät aktiviert wurden. Nach der ersten Aktivierung wird immer YES
zurückgegeben. Selbst wenn Sie sie in den Einstellungen (Benachrichtigungen) deaktivieren, wird dies YES
zurückgegeben. Dies liegt daran, dass sich eine App ab iOS8 für Remote-Benachrichtigungen registrieren und sogar an ein Gerät senden kann, ohne dass der Benutzer Benachrichtigungen aktiviert hat , Abzeichen und Ton, ohne dass der Benutzer das einschaltet. Stille Benachrichtigungen sind ein gutes Beispiel für etwas, das Sie möglicherweise auch bei deaktivierten Benachrichtigungen tun können.
Soweit currentUserNotificationSettings
gibt es eines von vier Dingen an:
Alarme sind aktiviert Badges sind aktiviert Sound ist eingeschaltet Keine sind aktiviert.
Auf diese Weise erhalten Sie keinerlei Hinweis auf die anderen Faktoren oder den Benachrichtigungsschalter.
Ein Benutzer kann zwar Ausweise, Töne und Warnungen deaktivieren, sich jedoch weiterhin auf dem Sperrbildschirm oder im Benachrichtigungscenter anzeigen lassen. Dieser Benutzer sollte weiterhin Push-Benachrichtigungen erhalten und diese sowohl auf dem Sperrbildschirm als auch im Benachrichtigungscenter sehen können. Sie haben die Benachrichtigung eingeschaltet. ABER currentUserNotificationSettings
wird in diesem Fall Folgendes zurückgeben: UIUserNotificationTypeNone
. Dies ist nicht wirklich ein Hinweis auf die tatsächlichen Einstellungen des Benutzers.
Ein paar Vermutungen kann man machen:
isRegisteredForRemoteNotifications
NO
ist, können Sie davon ausgehen, dass dieses Gerät niemals erfolgreich für Remote-Benachrichtigungen registriert wurde.application:didRegisterUserNotificationSettings:
mit den Einstellungen für Benutzerbenachrichtigungen vorgenommen, da zum ersten Mal ein Benutzer registriert wurde. Die Einstellungen sollten angeben, was der Benutzer in Bezug auf die Berechtigung ausgewählt hat anfordern. Wenn die Einstellungen einem anderen Wert als UIUserNotificationTypeNone
entsprechen, wurde die Push-Berechtigung erteilt, andernfalls wurde sie abgelehnt. Der Grund dafür ist, dass der Benutzer von dem Moment an, an dem der Fernregistrierungsprozess beginnt, nur noch die Möglichkeit hat, zu akzeptieren oder abzulehnen, wobei die anfänglichen Einstellungen einer Annahme die Einstellungen sind, die Sie während des Registrierungsprozesses festgelegt haben.Um die Antwort zu vervollständigen, könnte so etwas funktionieren ...
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
switch (types) {
case UIRemoteNotificationTypeAlert:
case UIRemoteNotificationTypeBadge:
// For enabled code
break;
case UIRemoteNotificationTypeSound:
case UIRemoteNotificationTypeNone:
default:
// For disabled code
break;
}
edit: Das ist nicht richtig. Da dies alles ein bisschen klug ist, funktioniert es nicht mit einem Switch.
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
UIRemoteNotificationType typesset = (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
if((types & typesset) == typesset)
{
CeldaSwitch.chkSwitch.on = true;
}
else
{
CeldaSwitch.chkSwitch.on = false;
}
Für iOS7 und davor sollten Sie tatsächlich enabledRemoteNotificationTypes
verwenden und prüfen, ob es UIRemoteNotificationTypeNone
entspricht (oder nicht gleich, je nachdem, was Sie möchten).
Für iOS8 ist es jedoch nicht immer genug, um nur mit isRegisteredForRemoteNotifications
so viele Zustände wie oben zu überprüfen. Sie sollten auch prüfen, ob application.currentUserNotificationSettings.types
gleich ist (oder nicht gleich, je nachdem, was Sie möchten) UIUserNotificationTypeNone
!
isRegisteredForRemoteNotifications
kann wahr zurückgeben, auch wenn currentUserNotificationSettings.types
UIUserNotificationTypeNone
zurückgibt.
iOS8 + (Ziel C)
#import <UserNotifications/UserNotifications.h>
[[UNUserNotificationCenter currentNotificationCenter]getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:{
break;
}
case UNAuthorizationStatusDenied:{
break;
}
case UNAuthorizationStatusAuthorized:{
break;
}
default:
break;
}
}];
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert)
// blah blah blah
{
NSLog(@"Notification Enabled");
}
else
{
NSLog(@"Notification not enabled");
}
Hier bekommen wir den UIRemoteNotificationType von UIApplication. Es stellt den Status der Push-Benachrichtigung dieser App in der Einstellung dar, und Sie können den Typ problemlos überprüfen
Ich versuche, iOS 10 und höher mit der von @Shaheen Ghiassy angebotenen Lösung zu unterstützen, finde jedoch ein Problem der Deprivation enabledRemoteNotificationTypes
. Also, die Lösung, die ich finde, indem ich isRegisteredForRemoteNotifications
anstelle von enabledRemoteNotificationTypes
verwende, was in iOS 8 veraltet ist. Nachfolgend finden Sie meine aktualisierte Lösung, die perfekt für mich funktioniert:
- (BOOL)notificationServicesEnabled {
BOOL isEnabled = NO;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){
UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
isEnabled = NO;
} else {
isEnabled = YES;
}
} else {
if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
isEnabled = YES;
} else{
isEnabled = NO;
}
}
return isEnabled;
}
Und wir können diese Funktion einfach aufrufen und auf ihren Bool
-Wert zugreifen und ihn folgendermaßen in den String-Wert konvertieren:
NSString *str = [self notificationServicesEnabled] ? @"YES" : @"NO";
Ich hoffe, es wird auch anderen helfen:) Viel Spaß beim Kodieren.
Obwohl Zacs Antwort bis zu iOS 7 vollkommen richtig war, hat sich das seit der Ankunft von iOS 8 geändert. Weil enabledRemoteNotificationTypes ab iOS 8 veraltet ist. Für iOS 8 und höher müssen Sie isRegisteredForRemoteNotifications verwenden.
Diese Swifty - Lösung funktionierte gut für mich (iOS8 +).
Methode:
func isNotificationEnabled(completion:@escaping (_ enabled:Bool)->()){
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
let status = (settings.authorizationStatus == .authorized)
completion(status)
})
} else {
if let status = UIApplication.shared.currentUserNotificationSettings?.types{
let status = status.rawValue != UIUserNotificationType(rawValue: 0).rawValue
completion(status)
}else{
completion(false)
}
}
}
Verwendungszweck:
isNotificationEnabled { (isEnabled) in
if isEnabled{
print("Push notification enabled")
}else{
print("Push notification not enabled")
}
}
In Xamarin funktionieren alle oben genannten Lösungen nicht für mich .. __ Dies verwende ich stattdessen:
public static bool IsRemoteNotificationsEnabled() {
return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}
Sie erhalten ein Live-Update, auch nachdem Sie den Benachrichtigungsstatus in den Einstellungen geändert haben.
re:
das ist richtig
if (types & UIRemoteNotificationTypeAlert)
aber das folgende ist auch richtig! (da UIRemoteNotificationTypeNone 0 ist)
if (types == UIRemoteNotificationTypeNone)
siehe folgendes
NSLog(@"log:%d",0 & 0); ///false
NSLog(@"log:%d",1 & 1); ///true
NSLog(@"log:%d",1<<1 & 1<<1); ///true
NSLog(@"log:%d",1<<2 & 1<<2); ///true
NSLog(@"log:%d",(0 & 0) && YES); ///false
NSLog(@"log:%d",(1 & 1) && YES); ///true
NSLog(@"log:%d",(1<<1 & 1<<1) && YES); ///true
NSLog(@"log:%d",(1<<2 & 1<<2) && YES); ///true
So geht's in Xamarin.ios.
public class NotificationUtils
{
public static bool AreNotificationsEnabled ()
{
var settings = UIApplication.SharedApplication.CurrentUserNotificationSettings;
var types = settings.Types;
return types != UIUserNotificationType.None;
}
}
Wenn Sie iOS 10+ unterstützen, verwenden Sie die UNUserNotificationCenter-Methode.