0

在我的入职申请中,我有一个UIPageViewController,其中包含一个用于授权通知的“引导”屏幕。用户将点击一个标签为“启用通知”的按钮,并出现通知权限对话框。我该如何做到这一点?如何在IBAction中要求通知许可?

回答

1

你可以把:

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. 

斯威夫特

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

请记住也在文件中添加import UserNotifications斯威夫特#import <UserNotifications/UserNotifications.h>Objective-C的,你必须IBAction,并确保Push Notificationtarget激活 - Capabilities - Push notification

0

的Objective-C:

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

'UIUserNotificationSettings'在iOS的10已经过时,你应该使用'UNNotificationSettings'代替。 https://developer.apple.com/documentation/uikit/uiusernotificationsettings – Mateusz