我尝试将此Objective-c代码翻译为swift:
目标c:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[[UIApplication sharedApplication] registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound
categories:nil]];
}
...
迅速:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
if UIApplication.instancesRespondToSelector("registerUserNotificationSettings:") {
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings.settingsForTypes([UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
}
...
API签名:
// categories may be nil or an empty set if custom user notification actions will not be used
+ (instancetype)settingsForTypes:(UIUserNotificationType)types
categories:(nullable NSSet<UIUserNotificationCategory *> *)categories; // instances of UIUserNotificationCategory
但是我得到了一个我不明白的错误。毕竟我将2个参数传递给otificationSettings.settingsForTypes
,而不是只有一个,因为编译器会抱怨。
答案 0 :(得分:3)
它告诉你的是你不需要调用类方法+settingsForTypes:categories:
来构造UIUserNotificationSettings对象 - 你只需使用它initializer。
let settings = UIUserNotificationSettings(forTypes: [ .Alert, .Badge, .Sound ], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
答案 1 :(得分:0)
Swift 3和4:
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
iOS 10 +:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
print("Permission granted: \(granted)")
}