如果用户未授予通知权限,则尝试显示UIAlert后应用程序崩溃[重复]

问题描述 投票:-1回答:1

我有以下代码,该代码旨在请求向用户发送通知的权限,然后,如果他们未授予许可,则该应用会以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?

ios swift xcode notifications
1个回答
0
投票

请考虑以下代码:

© www.soinside.com 2019 - 2024. All rights reserved.