Push Notifications
Push Notification Setup
1. Import the following in your Appdelegate:
AppDelegate.swift
import FirebaseCore
import FirebaseMessaging
import FirebaseInstanceID
import NotificationCenter
import UserNotifications
2. Implement the following methods:
AppDelegate.swift
// for push notification
extension AppDelegate: MessagingDelegate, UNUserNotificationCenterDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
CoreAdapter.updateFCMToken(fcmToken)
}
@objc func tokenRefreshNotification(notification: NSNotification)
{
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
let fcmToken = result.token
CoreAdapter.updateFCMToken(fcmToken)
}
}
}
/// register_for_notifications
func registerFirebaseSetup(_ application: UIApplication) {
if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
notificationLaunch = true
}
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
Messaging.messaging().isAutoInitEnabled = true
// [END set_messaging_delegate]
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
// Handle the message for firebase auth phone verification
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
// Handle it for firebase messaging analytics
if ((notification["gcm.message_id"]) != nil) {
Messaging.messaging().appDidReceiveMessage(notification)
}
}
// [END receive_message]
// Receive displayed notifications for iOS 10 devices.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UpdateifNotifi"), object: self, userInfo: nil)
// Print full message.
//print(userInfo)
// Change this to your preferred presentation option
//TODO: Handle foreground notification
completionHandler([.alert,.badge,.sound])
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
do {
try CoreAdapter.processDeeplink(deeplink: url.absoluteString)
} catch let error as NucleiSdkError {
print(error.localizedDescription)
} catch let error {
print(error)
}
if Auth.auth().canHandle(url) {
return true
}
return false
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod)
Auth.auth().setAPNSToken(deviceToken, type: .unknown) // Setting this to .unknown is what seems to have helped
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
//print(userInfo)
completionHandler()
NSLog("didReceiveRemoteNotification for iOS9: \(userInfo)")
DispatchQueue.main.async {
switch UIApplication.shared.applicationState {
case .active:
CoreAdapter.processNotification(userInfo as NSDictionary, self.notificationLaunch) { (nucleiNotificationHandler, deeplink) in
switch nucleiNotificationHandler {
case .nonNucleiPayload: break;
case .partnerAppNotLoggedIn:
print(deeplink)
break;
}
}
case .background:
CoreAdapter.processNotification(userInfo as NSDictionary,self.notificationLaunch) { (nucleiNotificationHandler, deeplink) in
switch nucleiNotificationHandler {
case .nonNucleiPayload: break;
case .partnerAppNotLoggedIn:
print(deeplink)
break;
}
}
default:
CoreAdapter.processNotification(userInfo as NSDictionary, self.notificationLaunch) { (nucleiNotificationHandler, deeplink) in
switch nucleiNotificationHandler {
case .nonNucleiPayload: break;
case .partnerAppNotLoggedIn:
print(deeplink)
break;
}
}
}
}
}
3. Register Firebase in Appdelegate’s func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
method:
registerFirebaseSetup(application)
4. Add this variable in Appdelegate’s file to access weather app is launched through notification
var notificationLaunch = false
5. Add this key in info.plist
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>