Lance Samaria
Lance Samaria

Reputation: 19622

Swift -How to change push notification && sound from within the app itself?

In my app I send silent push notifications "content-available": 1.

On the receiver's end they can go to the settings inside the app and toggle on notifications and the sound.

I know I can use this code to find out the status of either inside the app

UNUserNotificationCenter.current().getNotificationSettings { (settings: UNNotificationSettings) in
        guard settings.authorizationStatus == .authorized else { return }

        let soundSetting: UNNotificationSetting = settings.soundSetting
        switch soundSetting {
        case .enabled:
            print("enabled")
        case .disabled:
            print("disabled")
        case .notSupported:
            print("???")
        }

        let badgeSetting: UNNotificationSetting = settings.badgeSetting
        switch badgeSetting {
        case .enabled:
            print("enabled")
        case .disabled:
            print("disabled")
        case .notSupported:
            print("???")
        }

        UIApplication.shared.registerForRemoteNotifications()
    }

The question is how do I change the status of either the notification itself or the sound from within the app itself without sending the user outside the app?

lazy var switchNotificationControl: UISwitch = { ... }
lazy var switchSoundControl: UISwitch = { ... }

@objc func switchValueDidChange(_ sender: UISwitch) {
    if (sender.isOn == true) {

       // set notifications to on/true or sound to on/true
    } else {

       // set notifications to off/false or sound to off/false
    }
}

enter image description here

Upvotes: 0

Views: 1659

Answers (2)

Terry
Terry

Reputation: 108

It seems not be able to change it programatically once user accepts or denies the push notifications permission. You can refer this article from Apple.

The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

So the better way to turn on/off push notifications is better to do it from your server.

Upvotes: 1

Lance Samaria
Lance Samaria

Reputation: 19622

There doesn't seem a possible way to do this from within the app itself

https://stackoverflow.com/a/33520827/4833705

https://stackoverflow.com/a/36654919/4833705

Also I tried the code below and when Notifications were on (from outside the app) I used this to toggle them off and it didn't do anything.

@objc func switchValueDidChange(_ sender: UISwitch) {
    if (sender.isOn == true) {

       // *** doesn't work ***
       UIApplication.shared.registerForRemoteNotifications()

    } else {

       // *** doesn't work ***
       UIApplication.shared.unregisterForRemoteNotifications()
    }
}

Upvotes: 0

Related Questions