【问题标题】:How to enable/disable push notification from my app如何从我的应用启用/禁用推送通知
【发布时间】:2016-05-17 00:36:30
【问题描述】:

我正在开发具有推送通知属性的应用程序。我应该启用/禁用推送通知权限我的应用程序无需转到 iPhone 设置。

有没有办法实现它?

我搜索了很多,但我没有找到任何合适的方法来实现它。

有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果用户拒绝推送通知的权限,您不能让他在应用内启用它。

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

      【讨论】:

        猜你喜欢
        • 2012-11-28
        • 1970-01-01
        • 2012-05-16
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        • 2023-04-06
        • 2021-04-02
        • 1970-01-01
        相关资源
        最近更新 更多