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