2015-06-14 39 views
15

我似乎無法找到超越製作去年十一月(here),但我的舊代碼似乎並沒有爲我在Xcode 7的工作更多的和registerUserNotificationSettings任何文件斯威夫特2.在Swift 2中更改registerUserNotificationSettings?

我有這個代碼在應用程序委託:

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」沒有一個名爲「警告」

成員

不能援引「registerUserNotificationSettings」類型的參數列表「(UIUserNotificationSettings)」

我搜索過的任何變化的信息,但我找不到任何東西。我錯過了明顯的東西嗎?

回答

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

@取締的回答會的工作,但它是可能做到這一點更SWIFTY方式。除了使用NSSet以及向下投擲外,您還可以使用帶有一般類型UIUserNotificationCategory的Set進行建立。

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

還值得注意的是,將代碼分成多行可以幫助您確切地確定問題所在。在這種情況下,你的第二個錯誤僅僅是表達式被內聯後的第一個錯誤。

正如@stephencelis在他下面的評論中熟練地指出的那樣,Sets是ArrayLiteralConvertible,所以你可以一直減少到下面。

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

這當然看起來比我原來的代碼更好看 - 謝謝@ 0x7fffffff。 –