如果用户未授予通知权限,应用程序在尝试显示 UIAlert 后崩溃
App is crashing after trying to show a UIAlert if the user hasn't granted permission for notifications
我有以下代码,旨在请求向用户发送通知的权限,然后如果他们不授予权限,应用程序会以 UIAlert 的形式向他们发出警告 - 这是因为如果他们想要通知以及他们想要通知的时间,他们选择的上一个屏幕,因此他们不在这里授予权限是没有意义的。
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if !granted {
let permissionNotGrantedAlert = UIAlertController(title: "Notifications not enabled", message: "We won't be able to send you notifications.\n\nYou can allow us to send you notifications from your device's settings.", preferredStyle: .alert)
permissionNotGrantedAlert.addAction(UIAlertAction(title: "Go to settings", style: .default, handler: { action in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
}))
permissionNotGrantedAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
}))
self.present(permissionNotGrantedAlert, animated: true)
}
if let error = error {
print(error)
}
}
问题是应用程序运行时抛出了这个异常:
Exception: "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread."
并且此错误消息显示在控制台中:
[Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behaviour.
如果未授予权限,我该如何着手显示 UIAlert?
考虑以下代码:
DispatchQueue.main.async {
self.present(permissionNotGrantedAlert, animated: true)
}
我有以下代码,旨在请求向用户发送通知的权限,然后如果他们不授予权限,应用程序会以 UIAlert 的形式向他们发出警告 - 这是因为如果他们想要通知以及他们想要通知的时间,他们选择的上一个屏幕,因此他们不在这里授予权限是没有意义的。
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if !granted {
let permissionNotGrantedAlert = UIAlertController(title: "Notifications not enabled", message: "We won't be able to send you notifications.\n\nYou can allow us to send you notifications from your device's settings.", preferredStyle: .alert)
permissionNotGrantedAlert.addAction(UIAlertAction(title: "Go to settings", style: .default, handler: { action in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
}))
permissionNotGrantedAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
}))
self.present(permissionNotGrantedAlert, animated: true)
}
if let error = error {
print(error)
}
}
问题是应用程序运行时抛出了这个异常:
Exception: "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread."
并且此错误消息显示在控制台中:
[Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behaviour.
如果未授予权限,我该如何着手显示 UIAlert?
考虑以下代码:
DispatchQueue.main.async {
self.present(permissionNotGrantedAlert, animated: true)
}