IOS push notifications can be enhanced by using the following extensions:
- Notification Service Extension - modify/enhance the content of the notification
- Notification Content Extension - enhance the UI of the notification
It is possible to add buttons to a notification using the Notification Service Extension as described here, but lets say I want to use custom UI (and not the system default UI) to display those buttons. Notification Content Extension possess a view controller, where we can specify the UI of the notification. From iOS 12 onwards, it is possible to add custom buttons.
I created a Notification Content Extension and have added some code to display 3 buttons as shown below.
class NotificationViewController: UIViewController, UNNotificationContentExtension {
...
override func viewDidLoad() {
super.viewDidLoad()
}
// accept, tentative, decline are of type UIButton
func didReceive(_ pNotification: UNNotification) {
let screen_size: CGSize = self.view.frame.size
accept = UIButton(frame: CGRect(x: 0, y: 0, width: screen_size.width/3, height: 100))
accept?.setTitle("Accept", for: .normal)
accept?.backgroundColor = .blue
accept?.addTarget(self, action: #selector(onClicked), for: .touchUpInside)
self.view.addSubview(accept!)
tentative = UIButton(frame: CGRect(x: screen_size.width/3, y: 0, width: screen_size.width/3, height: 100))
tentative?.setTitle("Tentative", for: .normal)
tentative?.backgroundColor = .blue
tentative?.addTarget(self, action: #selector(onClicked), for: .touchUpInside)
self.view.addSubview(tentative!)
decline = UIButton(frame: CGRect(x: 2*(screen_size.width/3), y: 0, width: screen_size.width/3, height: 100))
decline?.setTitle("Decline", for: .normal)
decline?.backgroundColor = .blue
decline?.addTarget(self, action: #selector(onClicked), for: .touchUpInside)
self.view.addSubview(decline!)
view.backgroundColor = .cyan
}
@objc func onClicked(pClickedButton: UIButton) {
Log((String(format: "%@ button clicked!", pClickedButton.currentTitle!)))
}
}
It works. If I long press the default abbreviated interface (which cannot be customised), notification expands and shows the custom view containing those buttons (Accept, Tentative, Decline as shown above) in the notification interface.
With the above code, when user taps either of those buttons, a log statement gets printed and nothing happens (even the notification screen doesn't disappear, as it happens with regular notifications) - which is okay because that's how it's coded... for now.
But the expected behaviour is, clicked notification disappears from the notification centre and the app wakes up to process user's action - a click of a button on the notification interface. I'm not sure how to achieve this behaviour and there's not much about this on Notification Content Extension documentation.
Greatly appreciate any assistance.
PS: I'm very new to UI in iOS. Sorry.