允许推送通知版本控制

时间:2017-08-23 07:01:37

标签: ios swift version-control push-notification notifications

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])

}

3 个答案:

答案 0 :(得分:0)

试试这个:

const fetchAsync = async () => {
   const result = await fetch(url);
   const data = await result.json();
   return data.value.joke;
}

答案 1 :(得分:0)

是的,iOS 10的代码也适用于iOS 11。

基本上 #available 宏会检查最低操作系统,因此合并iOS 8和9也是安全的。

//iOS 10+
if #available(iOS 10, *) {
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in
        if (granted) { //check if authorization was granted before registering
            application.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])
}

答案 2 :(得分:0)

if #available(iOS 10, *)

读作:如果版本10或更高版本的iOS可用...

因此,如果您保留代码,并且iOS 11,12等即将发布,那么它们将全部进入此if分支。

因此,只要Push API未更改,您的代码就会正常工作。 如果Apple将来更改API(例如在iOS 12中),则必须添加另一个if-branch并将应用程序重新提交给商店......

(如果使用iOS 9的人使用你的应用,他们将会进入第二个if分支 - 因为第一个不适用。所以if s的顺序保证降低iOS版本得到正确的代码。)