Ios UIUserNotificationSettings的Swift 3.0语法更改

Ios UIUserNotificationSettings的Swift 3.0语法更改,ios,swift,uikit,Ios,Swift,Uikit,我正在使用swift 3.0,并试图将徽章编号添加到我的应用程序中。我相信正确的方法类似于下面的方法 application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: n

我正在使用swift 3.0,并试图将徽章编号添加到我的应用程序中。我相信正确的方法类似于下面的方法

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
            UIUserNotificationType.Badge, categories: nil
            ))

application.applicationIconBadgeNumber = 5

但是,我在
UIUserNotificationSettings
块中使用“|”时出错,如果我只有
UIUserNotificationType.badge
作为第一个参数,我还会收到
UIUserNotificationSettings
的错误“参数标签(forTypes,categories)与任何可用重载都不匹配”。swift 3.0是否更改了此语句的语法?

它已在swift 2和swift 3中更新。这一行可以解决您的问题。另外,请确保UIUserNotificationType的任何其他行的变量都已切换为小写

let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)

据我所知,
UIUserNotificationSettings
已不推荐用于iOS 10.0。现在建议您使用
UNUserNotificationCenter

以下是我为确保我的代码是最新的所做的:

1) 将
UserNotifications
框架导入您的
AppDelegate

导入用户通知

2) 在
AppDelegate
中的
didfishlaunchingwithoptions
函数中,添加以下内容:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

        if granted {
            UIApplication.shared.registerForRemoteNotifications()
        }

    }

    return true
}
注册并允许通知后,您可以随时更改徽章编号:

UIApplication.shared.applicationBadgeNumber=value

这对我来说很有效,我只是通过向手机发送远程通知来测试它,效果很好。希望这有帮助。

“rawValue”可以使用|运算符

这段代码在swift3中工作,但我们不需要这样做

let types = UIUserNotificationType(rawValue:UIUserNotificationType.alert.rawValue | UIUserNotificationType.sound.rawValue | UIUserNotificationType.badge.rawValue)

application.registerUserNotificationSettings(UIUserNotificationSettings(types: types, categories: nil))

Swift 3的所有语法都发生了变化,但您的语法甚至是在Swift 2之前。查看并启动Xcode中的“转换为当前Swift语法”转换器。或者阅读文档。我不在乎这些要点,但是你应该改变这个问题的正确答案,因为它在iOS 10.0中发生了变化。这是一个非常常见的问题,人们应该知道正确的答案是什么。目前,Swift 3+iOS 10使用无通知设置
UIUserNotificationSettings
已不推荐用于iOS 10.0。我在下面发布了一个关于当前推荐语法的答案。