iOS 7 需要相同的方法

Need same method for iOS 7

我正在开发一个 iOS 应用程序,我希望所有 iOS 7 及更高版本的手机都能够使用该应用程序。当我将其设置为 iOS 7 时,无法使用三种方法,因为它们仅适用于 iOS 8 及更新版本。有谁知道旧方法。这是有错误的代码...

let settings = UIUserNotificationSettings.init(forTypes: [.Sound, .Alert, .Badge], categories: nil) //Error: UIserNotificationSettings is only available on iOS 8 and newer 
application.registerUserNotificationSettings(settings) //Error:  registerUserNotificationSettings is only available on iOS 8 and newer 

application.registerForRemoteNotifications() //Error: registerForRemoteNotifications is only available on iOS 8 and newer 

我从 http://corinnekrych.blogspot.com.au/2014/07/how-to-support-push-notification-for.html 发现了如何让它工作并将其转换为 Swift:

if application.respondsToSelector("registerUserNotificationSettings:") {
    let settings = UIUserNotificationSettings.init(forTypes: [.Sound, .Alert, .Badge], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
    UIApplication.sharedApplication().registerForRemoteNotificationTypes([.Sound, .Alert, .Badge])
}
// Check to see if this is an iOS 8 device.
let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1)
if iOS8 {
    // Register for push in iOS 8
    let settings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    UIApplication.sharedApplication().registerForRemoteNotifications()
} else {        
    // Register for push in iOS 7
    UIApplication.sharedApplication().registerForRemoteNotificationTypes(UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert)
}

这对你有用吗?

如果您使用的是 swift 2.0,检查 OS 版本的新正确方法是:

if #available(iOS 9, *) {
    // do iOS 9 stuff here
} else {
    // do pre iOS 9 stuff here
}

所以在你的特定情况下,你会想要这样的东西。

if #available(iOS 8, *) {
    let settings = UIUserNotificationSettings.init(forTypes: [.Sound, .Alert, .Badge], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
    UIApplication.sharedApplication().registerForRemoteNotificationTypes([.Sound, .Alert, .Badge])
}

此外,如果您的最低部署目标超过您正在检查的目标(部署 9,但检查 8),编译器将警告您检查是多余的。