How to get notification authorization status in swift 3?
Okay I found it:
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if(settings.authorizationStatus == .authorized)
{
print("Push authorized")
}
else
{
print("Push not authorized")
}
}
code by: Kuba
How to listen to the changes in notification authorization Status
You can use following code for check whether app's notification setting is On/off.
func setPushPermission(){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if(settings.authorizationStatus == .authorized) {
self.pushPermission = .Allowed
} else if(settings.authorizationStatus == .denied) {
self.pushPermission = .Disallowed
} else {
self.pushPermission = .UnDefined
}
}
}else{
let notificationSettings = UIApplication.shared.currentUserNotificationSettings
let status = notificationSettings?.types.contains(.alert)
if status == true {
self.pushPermission = .Allowed
}
}
}
func registerForUserNotification(){
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [UNAuthorizationOptions.alert, UNAuthorizationOptions.sound, UNAuthorizationOptions.badge]) { (willAllow: Bool, error: Error?) in
if willAllow == true
{
self.pushPermission = .Allowed
//[[UIApplication sharedApplication] registerForRemoteNotifications];
// UIApplication.shared.registerForRemoteNotifications()
}else{
self.pushPermission = .Disallowed
}
NotificationCenter.default.post(name: NSNotification.Name("PushPermissionChaged"), object: nil)
}
UNUserNotificationCenter.current().delegate = self
}else{
let userNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
// Register User Notification Settings
UIApplication.shared.registerUserNotificationSettings(userNotificationSettings)
self.pushPermission = .Allowed
}
}
How to get notification permission status (Swift)?
As Leo says in his comment, you can't return a result from an async function. (The function UNUserNotificationCenter.current().center.getNotificationSettings()
returns immediately, before it has prompted the user to approve notifications. Once the user responds, getNotificationSettings calls its completion handler. Inside that completion handler, you need to call your completion handler.)
You need to rewrite your function to take a completion handler. Something like this:
func notificationStatus( completion: @escaping (Bool) -> Void) {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
let authorized = settings.authorizationStatus == .authorized
completion(authorized)
}
}
And then call it like this:
notificationStatus(completion: { authorized in
print("authorized = \(authorized)")
}
)
Or, using trailing closure syntax:
notificationStatus() { authorized in
print("authorized = \(authorized)")
}
Note that as pointed out by Leo Dabus below, you can skip the parens in the function call when using trailing closure syntax:
notificationStatus { authorized in
print("authorized = \(authorized)")
}
Swift ios check if remote push notifications are enabled in ios9 and ios10
Updated answer after iOS 10 is using UNUserNotificationCenter
.
First you need to import UserNotifications
then
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")
}
})
this code will work till iOS 9, for iOS 10 use the above code snippet.
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
// User is registered for notification
} else {
// Show alert user is not registered for notification
}
User Notification Center get Authorization Options Swift 3/4 ios10/11
You can still get the notification settings by:
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.alertSetting == .enabled {
//alert is enabled
}
}
As it's mentioned in apple doc
When the value of this property is UNNotificationSetting.enabled, the
app is authorized to display alerts.
notification permission ask question Swift
From documentation:
The first time your app makes this authorization request, the system prompts the user to grant or deny the request and records the user’s response. Subsequent authorization requests don’t prompt the user.
Blockquote
So basically you are trying to request permissions when they were already denied:
if(settings.authorizationStatus == .denied || settings.authorizationStatus == .notDetermined){
print("not granted or denied")
center.requestAuthorization(options: [.alert, .sound]){ (granted, error) in
}
}
You can't. You can only ask for permissions if authorizationStatus
is .notDetermined
. This answer describes the best strategy:
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .notDetermined {
print("not granted yet - ask the user")
center.requestAuthorization(options: [.alert, .sound]){ (granted, error) in
guard error == nil && granted else {
print("User denied permissions, or error occurred")
return
}
print("permissions granted")
}
} else if settings.authorizationStatus == .denied {
print("Notification permission was previously denied, tell the user to go to settings & privacy to re-enable")
} else if settings.authorizationStatus == .authorized {
print("Notification permission was already granted")
}
})
If you want to retest .notDetermined
state after permissions were granted or denied, you need to uninstall the app.
How to check location authorization status at the click of a button in iOS 14?
You're code works - but have you remembered to add the privacy usage descriptions to the info.plist file?
Add these two entries in the file with your own explanation in the value field, then it should popup in the simulator:
- Privacy - Location Always and When In Use Usage Description
- Privacy - Location When In Use Usage Description
How to detect if Authorisation Status changed when application is opened from Settings
Recheck location permission in applicationWillEnterForeground
in appDelegate.swift file and send notification to your view controller using notification observer
yourViewcontroller.swift
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateLocationPermission(notfication:)), name: "updateLocation", object: nil)
}
@objc func updateLocationPermission(notfication: NSNotification) {
print("location updated")
}
AppDelegate.swift
func applicationWillEnterForeground(_ application: UIApplication) {
let nc = NotificationCenter.default
nc.post(name: Notification.Name("updateLocation"), object: nil)
}
Related Topics
Textfield Delegate Shouldchangecharactersinrange
File Couldn't Be Opened Because You Don't Have Permission to View It Error
Send Mail with File Attachment
Swiftui - How to Get Coordinate/Position of Clicked Button
Navigationview Bar Material Invisible on iOS 15
Implementing Swift Protocol Methods in a Base Class
Xcode11 Error "Open(_:Options:Completionhandler:) Is Unavailable in Application Extensions"
Swift Protocol as Generic Parameter
Firebase and Reading Nested Data Using Swift
How to Use the "Handler" of Uialertaction to Call Another Uialertaction
Compile Time Key Path Checking in Swift
Why Are Properties of an Immutable Object Mutable in Swift
Checking User Location Permission Status on iOS 14
Uitableviewautomaticdimension Not Working on iOS 8
How to Customize the Title/Subtitle Font in Callout from Mkannotationview or Just Hide Them