Elad Benda
Elad Benda

Reputation: 36654

'settingsForTypes(_:categories:)' is unavailable: use object construction 'UIUserNotificationSettings(forTypes:categories:)'

I tried to translate this objective-c code to swift:

objective-c:

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
    [[UIApplication sharedApplication] registerUserNotificationSettings:
        [UIUserNotificationSettings settingsForTypes:
            UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound
                                          categories:nil]];
  }

...

swift:

    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 signature:

// 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

but I get an error which I dont understand. After all I pass 2 params to otificationSettings.settingsForTypes and not just one as the compiler complains.

How can I fix this? enter image description here

Upvotes: 2

Views: 452

Answers (2)

Ilias Karim
Ilias Karim

Reputation: 5371

Swift 3 and 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)")
}

Upvotes: 1

Noah Witherspoon
Noah Witherspoon

Reputation: 57139

What it’s telling you is that you don’t need to call the class method +settingsForTypes:categories: to construct the UIUserNotificationSettings object—you just use its initializer instead.

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

Upvotes: 3

Related Questions