6

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

有没有办法实现它?

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

有什么帮助吗?

4

2 回答 2

5

如果用户拒绝推送通知的权限,您不能让他从应用程序中启用它。

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

于 2016-02-07T08:22:47.643 回答
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()
于 2017-06-27T09:58:48.630 回答