我似乎找不到有关registerUserNotificationSettings的任何文档,超出去年11月制作的文档(here),但我的旧代码似乎在Xcode 7和Swift 2中不再适用于我。< / p>
我在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>))
我现在在最后一行代码中收到以下两个错误:
'Element.Protocol'没有名为'Alert'的成员
和
无法使用类型为'(UIUserNotificationSettings)'的参数列表调用'registerUserNotificationSettings'
我搜索了有关任何更改的信息,但我找不到任何内容。我错过了一些明显的东西吗?
答案 0 :(得分: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>))
答案 1 :(得分:21)
@Banning的答案会起作用,但可以用更加Swifty的方式做到这一点。您可以使用具有泛型类型NSSet
的Set从头开始构建此代码,而不是使用UIUserNotificationCategory
和向下转换。
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])