当minium目标平台是iOS 7.0时,如何在Swift中使用iOS 8.0 API?

时间:2015-12-18 15:54:22

标签: ios swift

今天,我正在学习通知。在 registerUserNotificationSettings(_:)定义下,在UIApplication Class Reference中,它说

  

"在安排任何本地通知之前,您必须调用registerUserNotificationSettings方法,让系统知道您计划向用户显示的警报类型(如果有)。"

registerUserNotificationSettings 仅适用于iOS 8.0或更高版本。那么如果我使用Swift,如何使它与iOS 7兼容?

2 个答案:

答案 0 :(得分:3)

您可以使用Swift 2中的可用性检查并使用适用于iOS7的registerForRemoteNotificationTypes

示例:

if #available(iOS 8.0, *) {
        let options: UIUserNotificationType =   [
            UIUserNotificationType.Alert,
            UIUserNotificationType.Badge,
            UIUserNotificationType.Sound
        ]

        let settings = UIUserNotificationSettings(forTypes: options, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    } else {
        let options: UIRemoteNotificationType = [UIRemoteNotificationType.Badge, UIRemoteNotificationType.Sound, UIRemoteNotificationType.Alert]
        UIApplication.sharedApplication().registerForRemoteNotificationTypes(options)
    }

答案 1 :(得分:1)

将代码放在if语句中以检查ios版本。

if #available(iOS 8, *) {
  // ios 8 and newer 
}
else {
  // ios 7 and older
}
相关问题