如何从应用启用/禁用推送通知?

在我的应用程序中,我想从我的应用程序本身的设置页面启用/禁用推送通知。任何人都可以建议我从应用程序打开/关闭通知中心的应用程序状态的解决方案?

您可以使用以下代码注册和取消注册远程通知。

使用以下代码注册RemoteNotification.means启用通知

//-- Set Notification if ([[UIApplication sharedApplication]respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) { // For iOS 8 and above [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; [[UIApplication sharedApplication] registerForRemoteNotifications]; } else { // For iOS < 8 [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)]; } 

并使用以下代码禁用它。

 [[UIApplication sharedApplication] unregisterForRemoteNotifications]; 

斯威夫特4

启用推送通知(从应用程序设置):

 if #available(iOS 10.0, *) { // SETUP FOR NOTIFICATION FOR iOS >= 10.0 let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in if error == nil{ DispatchQueue.main.async(execute: { UIApplication.shared.registerForRemoteNotifications() }) } } } else { // SETUP FOR NOTIFICATION FOR iOS < 10.0 let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) // This is an asynchronous method to retrieve a Device Token // Callbacks are in AppDelegate.swift // Success = didRegisterForRemoteNotificationsWithDeviceToken // Fail = didFailToRegisterForRemoteNotificationsWithError UIApplication.shared.registerForRemoteNotifications() } 

委派方法来处理推送通知

 @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // ...register device token with our Time Entry API server via REST } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { //print("DidFaildRegistration : Device token for push notifications: FAIL -- ") //print(error.localizedDescription) } 

禁用推送通知:

 UIApplication.shared.unregisterForRemoteNotifications() 
  • Apple关于推送通知的文档