如何在IBAction中申请通知权限?

时间:2017-10-15 17:33:17

标签: ios objective-c permissions notifications apple-push-notifications

在我的登机时,我有一个UIPageViewController在最后包含一个'引子'屏幕,用于授权通知。用户将点击标有“启用通知”的按钮,将出现通知权限对话框。我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

你可以把:

<强>目标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.

<强>夫特

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内。

请记住在目标C Swift import UserNotifications添加#import <UserNotifications/UserNotifications.h>,在IBAction的文件中添加 Objective-C 确保在Push Notification - target - Capabilities下激活Push notification

答案 1 :(得分:0)

目标-C:

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