对Swift 2中registerUserNotificationSettings的更改?

Ada*_*son 15 uilocalnotification swift swift2

我似乎找不到有关registerUserNotificationSettings的任何文档,超出了去年11月(这里)生成的文件,但我的旧代码似乎在Xcode 7和Swift 2中不再适用于我.

我在App Delegate中有这个代码:

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>))
Run Code Online (Sandbox Code Playgroud)

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

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

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

我搜索了有关任何变化的信息,但我找不到任何东西.我错过了一些明显的东西吗

Ban*_*ngs 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>))
Run Code Online (Sandbox Code Playgroud)


Mic*_*lum 21

@Banning的答案会起作用,但可以以更加Swifty的方式做到这一点.NSSet您可以使用具有泛型类型的Set从头开始构建它,而不是使用和向下转换UIUserNotificationCategory.

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

值得注意的是,将代码分解为多行将帮助您确定问题的确切位置.在这种情况下,您的第二个错误只是表达式内联后第一个错误的结果.

正如@stephencelis在下面的评论中熟练指出的那样,集合是ArrayLiteralConvertible,所以你可以将这一点减少到下面.

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: [restartGameCategory])
Run Code Online (Sandbox Code Playgroud)