[英]How can I write code that compiles with Xcode 9.x(iOS11) and Xcode10.x(iOS12) when using UNAuthorizationStatus.provisional?
Hello I have some switch
case
code that handles UNAuthorizationStatus, since iOS12 a new status has been added: .provisional
. 您好,我有一些处理UNAuthorizationStatus的switch
case
代码,因为iOS12已添加新状态: .provisional
。 In C or other old style compiler stuff I would write a precompiler directive to surround .provisional handling code however in swift that seems to lead to errors. 在C或其他旧式编译器中,我会编写一个预编译器指令来包围.provisional处理代码,但是这种处理似乎会导致错误。
private func checkNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
if #available(iOS 12.0, *) { // ERROR here
case .provisional: // ERROR here too
// Do my thing
}
case .authorized:
// Do my thing
case .notDetermined:
// Request authorization and if granted do my thing
case .denied:
// Do not do my thing
}
}
}
Errors: 错误:
Switch must be exhaustive 开关必须详尽无遗
All statements inside a switch must be covered by a 'case' or 'default' 开关内的所有语句必须用“ case”或“ default”覆盖
Is there any smart way of handling this? 有什么聪明的方法可以解决这个问题吗? I would like to avoid this because it is too long and repetitive: 我想避免这种情况,因为它太长且重复:
if #available(iOS 12.0, *) {
NUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .provisional:
...
}
} else {
NUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
...
}
}
You could do all common cases as normal and add the available checks in the default part like this 您可以像往常一样处理所有常见情况,并在默认部分中添加可用的检查,如下所示
NUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .stateX:
//do stuff
default:
if #available(iOS 12.0, *) {
if settings.authorizationStatus == .provisional {
//Handle case
}
}
}
}
This isn't the most elegant solution, but it's simple to use if else
instead of switch
. 这不是最优雅的解决方案,但是if else
使用if else
而不是switch
,则使用起来很简单。 In my case I remap .provisional
to .authorized
. 在我来说,我重新映射.provisional
到.authorized
。 Something like: 就像是:
func didTapNotificationsCell(authorizationStatus: UNAuthorizationStatus) {
if #available(iOS 12.0, *), authorizationStatus == .provisional {
handleCommonStatus(.authorized)
} else {
handleCommonStatus(authorizationStatus)
}
}
private func handleCommonStatus(_ status: UNAuthorizationStatus) {
if status == .authorized {
// Do something
} else if status == .notDetermined {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in
}
} else if status == .denied {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.