UIUserNotificationSettings的Swift 3.0语法更改

时间:2016-06-17 20:02:16

标签: ios swift uikit

我正在使用swift 3.0,并尝试在我的应用中添加徽章编号。我相信这样做的正确方法与以下内容类似。

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

application.applicationIconBadgeNumber = 5

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

3 个答案:

答案 0 :(得分:36)

它已在Swift 2和Swift 3中更新。此行应该可以解决您的问题。还要确保具有UIUserNotificationType的任何其他行已将其变量切换为小写。

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

答案 1 :(得分:15)

根据我的理解,iOS {10.0}已弃用UIUserNotificationSettings。现在建议您使用UNUserNotificationCenter

这是我为确保我的代码是最新的而做的:

1)在UserNotifications

中导入AppDelegate框架

import UserNotifications

2)在didFinishLaunchingWithOptions内的AppDelegate函数内添加以下内容:

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.applicationIconBadgeNumber = value

这对我有用,我刚刚通过向手机发送远程通知来测试它,它运行正常。希望这会有所帮助。

答案 2 :(得分:2)

" rawValue"可以用|操作

此代码适用于swift3,但我们并不需要这样做。

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

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