I have managed to schedule a notification and show it to the user when the app is running/not running in the foreground. Now I need to display a ViewController
upon the tap of this notification.
I understand that didReceiveRemoteNotification
is the function that is called when the user taps on a notification. In my case, This function is never fired.
AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
return true
}
//didReceiveRemoteNotification goes here
The didReceiveRemoteNotification function:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if ( application.applicationState == UIApplicationState.active)
{
print("Active")
// App is foreground and notification is recieved,
// Show a alert.
}
else if( application.applicationState == UIApplicationState.background)
{
print("Background")
// App is in background and notification is received,
// You can fetch required data here don't do anything with UI.
}
else if( application.applicationState == UIApplicationState.inactive)
{
print("Inactive")
// App came in foreground by used clicking on notification,
// Use userinfo for redirecting to specific view controller.
}
}
This is the entire Notification related code in my AppDelegate
. Am I missing something?
For
UserNotifications
framework you need to work withUNUserNotificationCenterDelegate
, so implementUNUserNotificationCenterDelegate
withAppDelegate
and set the delegate indidFinishLaunchingWithOptions
method.Now you need to implements
userNotificationCenter(_:willPresent:withCompletionHandler:)
anduserNotificationCenter(_:didReceive:withCompletionHandler:)
methods to get notification.You can also check this AppCoda tutorial
Introduction to User Notifications Framework in iOS 10
for more details.