The issue is caused because the alert is being shown from the background thread as the completion handler in getNotificationSettings is being run in the background thread. To prevent this crash present alert in the main thread am done the following changes in my code.
func checkNotificationAllowed(){
let data = defaults.object(forKey:"mute") as? Bool
print(data!)
if (data != nil) == true {
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")
DispatchQueue.main.async {[weak self] in
guard let weakSelf = self else {return}
let alert = UIAlertController(title: "Turn On Notifications".localized(), message: "Notifications are disabled. Please turn on app notifications to get device alerts.".localized(), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Don't Allow".localized(), style: .cancel, handler: { action in
self.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Allow".localized(), style: .destructive, handler: { action in
weakSelf.dismiss(animated: true, completion: nil)
}))
weakSelf.present(alert, animated: true, completion: nil)
}
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")
}
})
}
}
Topic:
Programming Languages
SubTopic:
Swift
Tags: