UIUserNotificationSettings的Swift 3.0语法更改

Lee*_*Lee 14 uikit ios swift

我正在使用swift 3.0,我正在尝试将徽章编号添加到我的应用程序中.我相信这样做的正确方法类似于下面的内容.

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

application.applicationIconBadgeNumber = 5
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*dge 36

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

let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
Run Code Online (Sandbox Code Playgroud)

  • Swift 3 + iOS 10使用UNNotificationSettings https://developer.apple.com/reference/usernotifications/unnotificationsettings (3认同)
  • "UIUserNotificationSettings"现已不再适用于iOS 10.0.我在下面发布了一个答案,说明当前推荐的语法是什么. (3认同)

Pie*_*rce 15

根据我的理解,UIUserNotificationSettingsiOS 10.0已被弃用.现在建议您使用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
}
Run Code Online (Sandbox Code Playgroud)

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

UIApplication.shared.applicationIconBadgeNumber = value

这对我有用,我只是通过向手机发送远程通知来测试它,它运行正常.希望这可以帮助.

  • 是的,你的回答是实际的iOS 10.0谢谢 (2认同)