【问题标题】:Swift 3.0 Syntax change for UIUserNotificationSettingsUIUserNotificationSettings 的 Swift 3.0 语法更改
【发布时间】:2016-10-19 18:18:07
【问题描述】:

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

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

application.applicationIconBadgeNumber = 5

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

【问题讨论】:

  • All 语法随着 Swift 3 的变化而改变,但你的语法甚至在 Swift 2 之前。看看stackoverflow.com/a/30763344/1187415 然后启动“转换为当前的 Swift 语法”转换器在 Xcode 中。或阅读文档。
  • 我不在乎这些点,但是您应该更改此问题的正确答案,因为它随着 iOS 10.0 的变化而改变。这是一个很常见的问题,人们现在应该知道正确答案是什么,

标签: ios swift uikit


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

据我了解,UIUserNotificationSettings 在 iOS 10.0 中已被弃用。现在建议您使用UNUserNotificationCenter。

为了确保我的代码是最新的,我采取了以下措施:

1) 在你的AppDelegate 中导入UserNotifications 框架

import UserNotifications

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

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

这对我有用,我只是通过向我的手机发送远程通知来测试它,它运行良好。希望这会有所帮助。

【讨论】:

    【解决方案3】:

    "rawValue" 可以使用 |运算符。

    此代码在 swift3 中有效,但我们不需要这样做。

    let types = UIUserNotificationType(rawValue:UIUserNotificationType.alert.rawValue | UIUserNotificationType.sound.rawValue | UIUserNotificationType.badge.rawValue)
    
    application.registerUserNotificationSettings(UIUserNotificationSettings(types: types, categories: nil))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2017-02-04
      • 2017-01-05
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多