【发布时间】:2017-08-23 07:01:37
【问题描述】:
Swift 3 IOS 10:我一直在寻找允许推送通知的代码;最后,我可以从www.codementor.io 找到一个非常有用的。然而,我陷入了困惑。我想知道以下代码是否适用于较低或较新版本的 iOS。既然 Apple 将无情地发布它的版本,那么下面的代码将如何处理这些变化?有没有办法解决我提到的问题?
// iOS 10 support
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
【问题讨论】:
-
您的代码是正确的。只需将 iOS 9、8 和 7 组合成一个块即可。 iOS 10 在单独的块中。
-
如果我这样做了,如果新发布的iOS版本开始使用,这段代码还会生效吗?谢谢你的回答。
-
您正在检查#available 标记,这将验证设备的操作系统版本并执行该块。从 iOS 10 到现在(iOS 11),仍然使用 UNUserNotification 类。 Apple 更改此框架后,您必须像现在为 iOS 10 所做的那样支持新框架。
-
@Basheer,非常感谢!!
标签: ios swift version-control push-notification notifications