Silent notifications, also known as background or "content-available" notifications, are a type of push notification in iOS that allows apps to receive data in the background without displaying any alert, sound, or badge to the user. This is useful for updating content in the app or performing specific tasks without user intervention.
Setting Up Silent Notifications
In case you don't ask for Push Notifications permissions because you want to send only silent notifications, you need to call registerForRemoteNotifications()
method.
import SwiftUI
UIApplication.shared.registerForRemoteNotifications()
On the other side, you need to enable Remote Notifications capability.
Sending a Silent Notification
Silent notifications contain only one required parameter: content-available
. Then we can add our custom data as usual.
{
"aps": {
"content-available": 1
},
"user": {
"id": 1,
"name": "pablo"
}
}
Handling Silent Notifications
To handle silent notifications, implement the proper delegate method in your AppDelegate
. This method is called when a silent notification is received, allowing you to perform tasks like data fetching or local updates.
@MainActor
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any]
) async -> UIBackgroundFetchResult {
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)
}
return .newData
}
Unfortunately, this cannot be tested in the simulator.
Be the first to comment