Ans : Push notifications allow developers to reach users and perform small tasks even when users aren’t actively using an app.
In iOS 10, User can do following task :
- Display a short text message
- Play a notification sound
- Set a badge number on the app’s icon
- Provide actions the user can take without opening the app
- Show a media attachment
- Be silent, allowing the app to wake up in the background and perform a task
Now following steps to follow to configure push notification :
1. Create app id in developer account with your app bundle id. Push notification entitlement must be enabled for this app id. (or another way for go to App Settings > Capabilities and enable push notification switch). You also have to create CSR(Certificate Signing Request) file from your keychain and assign to this app id push notification feature in developer account.
2. Now in terms of coding, first we need to ask to user for allowing user notification. After allowing, we need to register for remote notification. If all goes good, system provides you 'token' which is address of this app for this device.
3. In code, first import usernotification. Then for registering for remote notification, in didFnishLaunchingWithOptions,
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
UIApplication.shared.registerForRemoteNotifications()
}
}
4. If registered for remote notification successfully, then one of the following two method will be called,
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
5. Device token is provided by APNS and this token will be converted to string. This device token shold be sent to application server or stored to database on server side.
Now lets study about payload or notification message,
Payload looks like :
{
"aps": {
"alert": "Breaking News!",
"sound": "default",
"link_url": "https://raywenderlich.com"
}
}
aps is fixed key in payload dictionary json. aps is also dictionary itself.
alert : Display text message
sound : Which sound when notification come
link_url : custom key, we can any such custom key for data
badge : number of count of badge that is displayed on app icon
category : which type of custom action notification have
Payload maximum size is 4096 kb (4 mb).
Now what when notification comes
1. If app is closed didFinishLaunchingWithOptions is called.
2. If open in background or foreground, then didReceiveRemoteNotification is called.
For 1st case,
In didFinishLaunchingWithOptions method
// Check if launched from notification
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
let aps = notification["aps"] as! [String: AnyObject]
_ = NewsItem.makeNewsItem(aps)
(window?.rootViewController as? UITabBarController)?.selectedIndex = 1
}
For 2nd case,
In didReceiveRemoteNotification,
let aps = userInfo["aps"] as! [String: AnyObject]
_ = NewsItem.makeNewsItem(aps)
Actionable Notification
Actionable notifications let you add custom buttons to the notification. You can put reply,retweet,like button as you seen our favourite apps. This type of notification can be defined by Category.
In this type notification, we have to register category like following instead of UIApplication.shared.registerForRemoteNotifications().
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
// 1
let viewAction = UNNotificationAction(identifier: viewActionIdentifier,
title: "View",
options: [.foreground])
// 2
let newsCategory = UNNotificationCategory(identifier: newsCategoryIdentifier,
actions: [viewAction],
intentIdentifiers: [],
options: [])
// 3
UNUserNotificationCenter.current().setNotificationCategories([newsCategory])
self.getNotificationSettings()
}
}
Above things is not enough for taking action on button. We have to add extension of UNUserNotificationCenterDelegate.
Silent Notification
If we want to do something task without knowing to user in background, then we can send silent notification to user device. For this background modes of push notification must be checked. For push notification aps, there is key named content-available. That's value should be 1 for silent notification.
For more detail,
click here.