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

时间:2016-02-07 08:05:58

标签: ios objective-c swift push-notification remote-notifications

我正在使用具有推送通知属性的App。我应该启用/禁用 我的应用中的推送通知权限,而无需转到iPhone设置。

有没有办法实现呢?

我搜索了很多,但我找不到任何正确的方法来实现它。

任何帮助?

2 个答案:

答案 0 :(得分:4)

如果用户拒绝了推送通知的权限,则无法让他从应用内启用它。

但是,您可以在设置应用中设置一个按钮(ViewController),然后让用户关闭和关闭通知。然后,您可以在发送通知之前设置要检查的布尔值。这样,用户可以使用它而不是禁用应用程序设备设置的通知权限。

答案 1 :(得分:2)

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

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()