Reputation: 36654
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.
Upvotes: 2
Views: 452
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
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