You can add additional data to notifications, enabling actions tailored to each specific notification.
Place your custom fields at the root level of the remote notification JSON.
{
"aps": {
"alert": {
"title": "EducaSwift",
"subtitle": "Remote Notifications",
"body": "This is a Remote Push Notification test.",
},
"badge": 12
},
"custom_field": "1",
"another_custom_field": "2"
}
For local notifications, you can add this info to the content:
let content = UNMutableNotificationContent()
content.title = "EducaSwift"
content.body = "This is a Local Push Notification test."
content.userInfo = [
"custom_field": 1,
"another_custom_field": 2
]
On both cases, when a notification is tapped we can read those custom fields:
@MainActor
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let userInfo = response.notification.request.content.userInfo
print(userInfo["custom_field"])
print(userInfo["another_custom_field"])
}
Using Decodable protocol
You can pass nested JSON parameters and decode them using JSONDecoder().
{
"aps": {
"alert": {
"title": "EducaSwift",
"subtitle": "Remote Notifications",
"body": "This is a Remote Push Notification test.",
},
"badge": 12
},
"user": {
"id": 1,
"name": "pablo"
}
}
struct User: Decodable {
let id: Int
let name: String
}
@MainActor
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let userInfo = response.notification.request.content.userInfo
if let userDictionary = userInfo["user"],
let userData = try? JSONSerialization.data(withJSONObject: userDictionary),
let user = try? JSONDecoder().decode(User.self, from: userData)
{
print(user.id)
print(user.name)
}
}
Be the first to comment