如何在 IBAction 中请求通知权限?
How do I ask for notifications permission in an IBAction?
在我的入门指南中,我有一个 UIPageViewController
,最后包含一个“入门”屏幕,用于授权通知。用户将点击标有“启用通知”的按钮,然后将出现通知权限对话框。我该如何实现?
你可以输入:
Objective-C
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
}];
[[UIApplication sharedApplication] registerForRemoteNotifications]; // you can also set here for local notification.
Swift
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
UIApplication.shared.registerForRemoteNotifications() // you can also set here for local notification.
在你的 IBAction
.
里面
请记住还要为 Swift 添加 import UserNotifications
或为 Objective-C[=34 添加 #import <UserNotifications/UserNotifications.h>
=] 在你有 IBAction
的文件中,并确保 Push Notification
在 target
- Capabilities
- Push notification
.
下激活
Objective-C:
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
在我的入门指南中,我有一个 UIPageViewController
,最后包含一个“入门”屏幕,用于授权通知。用户将点击标有“启用通知”的按钮,然后将出现通知权限对话框。我该如何实现?
你可以输入:
Objective-C
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
}];
[[UIApplication sharedApplication] registerForRemoteNotifications]; // you can also set here for local notification.
Swift
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
UIApplication.shared.registerForRemoteNotifications() // you can also set here for local notification.
在你的 IBAction
.
请记住还要为 Swift 添加 import UserNotifications
或为 Objective-C[=34 添加 #import <UserNotifications/UserNotifications.h>
=] 在你有 IBAction
的文件中,并确保 Push Notification
在 target
- Capabilities
- Push notification
.
Objective-C:
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}