' settingsForTypes(_:类:)'不可用:使用对象构造&UIUserNotificationSettings(forTypes:categories :)'

时间:2016-01-20 23:33:55

标签: ios objective-c swift appdelegate

我尝试将此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,而不是只有一个,因为编译器会抱怨。

我该如何解决这个问题? enter image description here

2 个答案:

答案 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)")
}