Swift 2中registerUserNotificationSettings的更改?

15

似乎没有找到有关registerUserNotificationSettings的更多文档,除了去年11月份(这里)发布的内容。但是,我的旧代码在Xcode 7和Swift 2中似乎不再起作用。

我在AppDelegate中有以下代码:

let endGameAction = UIMutableUserNotificationAction()
endGameAction.identifier = "END_GAME"
endGameAction.title = "End Game"
endGameAction.activationMode = .Background
endGameAction.authenticationRequired = false
endGameAction.destructive = true

let continueGameAction = UIMutableUserNotificationAction()
continueGameAction.identifier = "CONTINUE_GAME"
continueGameAction.title = "Continue"
continueGameAction.activationMode = .Foreground
continueGameAction.authenticationRequired = false
continueGameAction.destructive = false

let restartGameCategory = UIMutableUserNotificationCategory()
restartGameCategory.identifier = "RESTART_CATEGORY"
restartGameCategory.setActions([continueGameAction, endGameAction], forContext: .Default)
restartGameCategory.setActions([endGameAction, continueGameAction], forContext: .Minimal)

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: (NSSet(array: [restartGameCategory])) as Set<NSObject>))

现在我在代码的最后一行收到以下两个错误消息:

'Element.Protocol' 没有名为 'Alert' 的成员

无法使用类型为 '(UIUserNotificationSettings)' 的参数列表调用 'registerUserNotificationSettings'

我已经搜索了任何更改的信息,但是我找不到任何东西。 我是否错过了一些显而易见的东西?

2个回答

30

不要使用(NSSet(array: [restartGameCategory])) as Set<NSObject>)(NSSet(array: [restartGameCategory])) as? Set<UIUserNotificationCategory>),请改为:

application.registerUserNotificationSettings(
    UIUserNotificationSettings(
        forTypes: [.Alert, .Badge, .Sound],
        categories: (NSSet(array: [restartGameCategory])) as? Set<UIUserNotificationCategory>))

21

@Banning的答案是可行的,但是有一种更Swifty的方法可以实现。你可以使用带有泛型类型UIUserNotificationCategory的Set从基础构建这个集合,而不是使用NSSet和向下转换。

let categories = Set<UIUserNotificationCategory>(arrayLiteral: restartGameCategory)
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: categories)
application.registerUserNotificationSettings(settings)

值得注意的是,将代码分成多行有助于您准确地确定问题所在。在这种情况下,第二个错误仅是第一个错误的结果,因为表达式是内联的。

正如@stephencelis在下面的评论中所指出的那样,集合是ArrayLiteralConvertible,因此您可以将其缩减到以下内容。

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: [restartGameCategory])

这看起来比我的原始代码整洁多了 - 谢谢,@0x7fffffff。 - Adam Johnson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接