We have a messaging app that aims to display notifications when it receives messages when phone is locked from remote user, and let local user enter text from lock screen, and s
There is lack of well-structured info in internet, although it's very good feature, implemented in serious messenger apps.
You should start with UNNotificationContentExtension
to show custom UI for received Push Notification. Take any available example on internet and implement it like you want. Pay attention on bundle ID - it should be com.yourapp.yourextension
. When done, you'll have the main app and the extension widget in Xcode.
In the main app set up registration for Push Notifications in iOS10 manner:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
guard granted else { return }
let replyAction = UNTextInputNotificationAction(identifier: "ReplyAction", title: "Reply", options: [])
let openAppAction = UNNotificationAction(identifier: "OpenAppAction", title: "Open app", options: [.foreground])
let quickReplyCategory = UNNotificationCategory(identifier: "QuickReply", actions: [replyAction, openAppAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([quickReplyCategory])
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
guard settings.authorizationStatus == .authorized else { return }
UIApplication.shared.registerForRemoteNotifications()
}
}
All magic happens in UNTextInputNotificationAction
custom action that you add to your Push Notifications handler.
To complete setting up Push Notifications add this param in your extension Info.plist
: NSExtension -> NSExtensionAttributes -> UNNotificationExtensionCategory: "QuickReply"
It's all about setting up. To try it, use Pusher
tool and configure Push Notification in this manner:
{
"aps": {
"alert":"Trigger quick reply",
"category":"QuickReply"
}
}
At least you have to catch the notification in your widget. It happens in func didReceive(_ notification: UNNotification)
in your widget class:
func didReceive(_ notification: UNNotification) {
let message = notification.request.content.body
let userInfo = notification.request.content.userInfo
// populate data from received Push Notification in your widget UI...
}
And if user responds to received Push Notification, your widget will trigger the following callback:
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
if response.actionIdentifier == "ReplyAction" {
if let textResponse = response as? UNTextInputNotificationResponse {
// Do whatever you like with user text response...
completion(.doNotDismiss)
return
}
}
completion(.dismiss)
}