27

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

4

2 回答 2

63

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

使用以下代码注册 RemoteNotification ..意味着启用通知

//-- 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];
于 2012-12-11T06:15:28.447 回答
14

斯威夫特 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()
于 2017-06-21T09:57:11.047 回答