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

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

问题描述:

我试图把这种Objective-C代码来迅速:'settingsForTypes(_:类:)' 是不可用:使用对象构造 'UIUserNotificationSettings(forTypes:类别:)'

的Objective-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 

但我得到一个我不明白的错误。毕竟我将两个参数传递给otificationSettings.settingsForTypes,而不仅仅是一个,因为编译器会抱怨。

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

什么它告诉你的是,你不需要调用类方法+settingsForTypes:categories:构建UIUserNotificationSettings对象的你只是用它来代替initializer

let settings = UIUserNotificationSettings(forTypes: [ .Alert, .Badge, .Sound ], categories: nil) 
UIApplication.sharedApplication().registerUserNotificationSettings(settings) 

夫特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)") 
}