Tap Push Notification Action
Instagram Firebase
Each push notification can be handled with different types of actions if programmed correctly. Today, we perform the action of loading a follower's profile into our UI whenever we tap on the push notification. This feature requires us to include the follower's user id in the notification object from our Cloud Function. Finally we add some custom logic in our AppDelegate file to handle these notifications.

Comments (23)
rehannali
5 years ago
Hi Brain, I've learnt a lot from this tutorial. I have a question, how can we manage all versions of ios i.e. this tutorial is for 10.* or above? What if user is using 9.* or below?
wasim
5 years ago
I think you need to check firebase docs for that. but here's firebase code to handle prev. versions https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExampleSwift/AppDelegate.swift#L40-L55
Share App
5 years ago
Awesome! Thanks!
Vartis
5 years ago
Hi Brian, maybe I’m doing something wrong here but I notice that if I create a new user from my iPhone, log out, create another one, then follow the first one, I’m getting a notification from the first user. And this doesn’t happened when I follow a user created on the simulator. Are you getting this too or I’m I missing something? Thanks! Hope my English wasn’t too bad and I was clear enough
Brian Voong
5 years ago
Maxnelson997
5 years ago
Excellent course Brian. Learned some great concepts & practices throughout this course. Will recommend to my developer buddies on Instagram!
Brian Voong
5 years ago
josiahsavino
5 years ago
Thank you so much for the notification series. Once I updated to xcode 4 I was able to get notifications to send from one device to another device today for the first time showing following and linking correctly. Problem is I force quit the applications on both of my external devices and now neither of them are receiving notifications anymore.? Note I tried resetting my mac, resetting the function.js file, reopening swift, redeploying the function file in Atom which worked. Log showing healthy but still not receiving notifications anymore. Any ideas?
josiahsavino
5 years ago
So I created a new user for the social app I am making and it was able to receive the notifications. This means that when I forced the App to close somehow the FCM token changed or something? This is bad news. Lots of people use for close on Apps to help with battery life. How can we let users force close app without the FCM changing?
josiahsavino
5 years ago
Can the extra bonus video be on receiving different function types of notifications? For example I have notifications going for one of my functions that works great However I need notifications going for at least three different functions. One function needs logic for the index.js file. For example when checked = true(Boolean) for a specific branch. What do you think?
PatrickVB
5 years ago
With Push Notifications, to add sound, what additional code do I need in the AppDelegate besides the below code in didFinishLaunchingWithOptions /// Sound? UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in // Enable or disable features based on authorization let content = UNMutableNotificationContent() content.sound = UNNotificationSound.default() Thank You
Brian Voong
5 years ago
PatrickVB
5 years ago
Awesome! Thank You.
PatrickVB
5 years ago
Am I putting this code addition in the payload section of notification under exports.sendPushNotifications below the title: and body: ?? Thank You
Brian Voong
5 years ago
PatrickVB
5 years ago
This does not seem to trigger sound. I even went into firebase -> Notifications -> New Message and under Advanced options: sound enabled
PatrickVB
5 years ago
Still doesn't seem to work even though code compiles. This may be a Good Quick Episode? Thanks!
PatrickVB
5 years ago
Good News! I Have the sound working. Just needed additional coding in App Delegate. I needed to use AudioServicesPlaySystem Sound
PatrickVB
5 years ago
Good Day! I figured out the Sound portion of the Push Notification. And I am working on the Badge Icon when receiving Push Notifications. I can make the badge number show up with this code: private func attemptRegisterForNotifications....... /// Adds A Default Number In The Badge Location UNUserNotificationCenter.current().delegate = self UNNotificationSound.default() sound = UNNotificationSound.default() UIApplication.shared.applicationIconBadgeNumber = 1 How do I programmatically increment the badge number with Firebase Push Notifications? Thank You - Patrick
esong2288
4 years ago
Hey Patrick, if you can, do you mind explaining how exactly you were able to achieve sound with the push notification? I'm having trouble figuring that out.
Obrac
5 years ago
Hey Brian, I seem to be getting an error of completionHandler not being called...I get the notifications, and they seem to be getting the info however when I tap nothing happens on the UI and the error prints in the console. FYI, I am using the simulator and my personal device for this. Any idea what may be causing this?
Brian Voong
5 years ago
Obrac
5 years ago
I have it set up like this... func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Added firebase for user authentication FirebaseApp.configure() // hijack appdelegate to redirec logged in users to explore window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() window?.rootViewController = mainTabBarController() // Request permission from user before fetching userLocation let locationManager = userLocationListener.shared locationManager.requestAlwaysAuthorization() // Adds the Fabric (Crashlytics( frameworks for crash/bugs reporting Fabric.with([Crashlytics.self]) // Register for notifications registerForNotifications(application: application) // Override point for customization after application launch. return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("Register for notifications: ", deviceToken) } // Registration token func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Registered with FCM token:", fcmToken) } // Listen for user notification func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let followerId = userInfo["followerId"] as? String { print(followerId) // Push new follower homeProfile let userHomeProfile = homeController(collectionViewLayout: UICollectionViewFlowLayout()) userHomeProfile.userId = followerId // Access mainUI from AppDelegate if let mainTabBar = window?.rootViewController as? mainTabBarController { // Allows access to notification window from any where in the mainTabar mainTabBar.selectedIndex = 0 // Dismisses viewController when accessing push notification views mainTabBar.presentedViewController?.dismiss(animated: true, completion: nil) if let homeProfile = mainTabBar.viewControllers?.first as? UINavigationController { homeProfile.pushViewController(userHomeProfile, animated: true) } } } } // APNS setup private func registerForNotifications(application: UIApplication) { print("Attempting to register APNS...") // Notifies self when register is successful Messaging.messaging().delegate = self // Set delegate UNUserNotificationCenter.current().delegate = self // User notifications auth // target IOs 10+ let options: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, error) in // Returns error on request if let error = error { print("Failed to request auth:", error) return } // Auth request is granted if granted { print("Auth granted") } else { // Auth is denied print("Auth denied") } } application.registerForRemoteNotifications() }
Brian Voong
5 years ago
Obrac
5 years ago
Ok, so I tried that earlier. I placed a bk in several lines inside the method and what seemed to be happening was that it would return the userInfo and followerId and immediately exit the function without calling the viewController, right after the first if/let.
Brian Voong
5 years ago
Obrac
5 years ago
How can I tackle this? I've pretty much followed the in your footsteps during the FCN part of the course, with very minor changes, where could the problem be coming from? the index.js? or swift files? I get the userId in the notifications by the way. PS...my simulator user doesn't have an fcmToken...could that be it?
Brian Voong
5 years ago
Obrac
5 years ago
Alright, so I'll try a few more times and get back to you. I'am only using the simulator for generating the notifications on my Iphone rather than receiving them. Thanks for the feedback Brian. Ohh, one more thing Brian, could you please get back to me on my question from here: https://www.letsbuildthatapp.com/course_video?id=1412, I'd really appreciate it. I'm still having trouble with this part and I've tried everything to date. Thanks!
Obrac
5 years ago
Hey Brian, So after some back and forth I was able to get it working. I'll be more careful with the typos in JS from now on. I had mistakenly written following instead of follower..go figure. Thanks for your help man.
stonypig1
5 years ago
There is an error or a part need to modify( correct if I am wrong), Mr.brian hand hard-coded the UID for great tea pot user in firebase cloud function, so only this user will work ?! do we suppose to figure it out dynamically by code or I misunderstand some parts.
stonypig1
5 years ago
Has anyone noticed if you remove the app(maybe also happen when app updating) and reinstall again, the cfmToken is resigned by apple, once the user sign in, the old token stored and later retrieved from firebase is no longer valid, anyone find a mechanism to check it and update the value ? can we set the logic code in the didreceivetoken function ? if current assigned is not match from firebase, restore the new one. if anyone have a clue please share. thanks
sgrpatel5600
5 years ago
how to do tap on notification if not using tab bar controller... i am using a window?.rootViewController = UINavigationController(rootViewController: HomeController()) how can i get access to this... please help...
sgrpatel5600
5 years ago
sorry got it...
magic
5 years ago
Great Tutorial as always
edison1
5 years ago
how do you implement the function to show the number of posts and comments and all of that?
samisays11
5 years ago
observe your database node where you have post or comment, in the call back func call snapshot.childcount, convert it to Int from UnInt. example Database.database.ref(post).postid.observe(snapshot) let postCount = Int(snapshot.childrenCount) numberOfPostLabel.text = String(postCount) same thing applies to comment count. its really simple.
edison1
5 years ago
thank you!!! it was so easy haha, that is why there's good people like you out there haha! thank you!!! btw how would i do the count of people who are following, since we don't necessarily, have a node for that?
Ryuichi Yamashita
5 years ago
Brian, thank you for great tutorial. If you have any chance, please add one more video that shows how to send liked or commented photo image with Push Notification via FCM. I struggle for several days, but I cannot...
benpalmer661
5 years ago
Brian, could you do a video the notification contains actions , like , view profile and and send message and each on takes you to a seperate screen? I want to learn how to call functions from the notification action buttons
Zlatko Petrov
5 years ago
Hey Brian, I thank you very much for all the hard work in putting together such a great and inspirational content. I am a huge fan of all your courses - both free and paid. Keep the good work up. I think it would be very helpful if you share some thoughts / hints / good practices / examples on how to process APNs when app is in different states. Thx again and best regards, Zlatko
esong2288
4 years ago
To implement sound with the push notification, do you just have to add "sound: 'default'" under notification in the payload or is there more I'm missing.
Clint Larenz Nurse
4 years ago
var payload = { notification: { title: "You have a new follower", body: userDoingTheFollowing.username + ' is now following you.', sound: 'default' },
Cabraham
4 years ago
thank you !!
Saurabh Tripathi
4 years ago
Please make tutorial to Push Notification via FCM.
Brian Voong
4 years ago
Clint Larenz Nurse
4 years ago
Interesting issue, so the nav bar title for the username display is using my app home page app name font, but when I click into my profile tab, it uses the regular font similar to what you had in this video.
Clint Larenz Nurse
4 years ago
Hey Brain, you probably don’t have time for this but it’s worth a shot. I’m getting push notifications if I comment/ like my own posts. Anyway you can omit yourself from that?
Hanisa Mohamed
3 years ago
You can use a simple if statement.
Lai Yit Ming
3 years ago
Hi Brian, I face similar issue with AppDelegate.swift that happened to me in Chapter #1 before. Specifically, I am using Xcode 11.6, there is unexpected null value return from: window?.rootViewController in func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive at minute 11:00 to 11:10. See below: func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let followerId = userInfo["followerId"] as? String { print(followerId) let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout()) userProfileController.userId = followerId if let mainTabBarController = window?.rootViewController as? MainTabBarController { mainTabBarController.selectedIndex = 0 mainTabBarController.presentedViewController?.dismiss(animated: true, completion:nil) if let homeNavigationController = mainTabBarController.viewControllers?.first as? UINavigationController { homeNavigationController.pushViewController(userProfileController, animated: true) } } else { print("mainTanBarController is null!!") } } } I trace the code in run time, it printed "mainTanBarController is null!!" Anyway I can fix this?
Lai Yit Ming
3 years ago
Sorry typo: I mean, can help me to fix this issue?
Brian Voong
3 years ago
Lai Yit Ming
3 years ago
It works, thanks you very much!!
HELP & SUPPORT