【问题标题】:App is crashing after trying to show a UIAlert if the user hasn't granted permission for notifications [duplicate]如果用户未授予通知权限,则应用程序在尝试显示 UIAlert 后崩溃 [重复]
【发布时间】:2020-09-18 00:40:11
【问题描述】:

我有以下代码,它旨在请求向用户发送通知的权限,然后如果他们不授予权限,应用程序会以 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】:

    考虑以下代码:

    DispatchQueue.main.async {
        self.present(permissionNotGrantedAlert, animated: true)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多