0

I am working with iOS Swift Notifications Module. I'm not getting the Alert/Banner Notification on the device.

I’m able to get notification when the App is open i.e. in Foreground, but not when app in in Background or Terminated.

Following is my code

import UIKit

import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

    var window: UIWindow?

    //  MARK: - Application Life Cycle
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FIRApp.configure()

        askNotificationPermission(application)

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        connectToFcm()

        return true
    }

    // MARK:- Push Notification Delegate Methods
    @nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
        print(appdata)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }

    // 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
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        print("%@", userInfo)
    }

    //  MARK: - Permissions
    func askNotificationPermission(_ application: UIApplication) {
        if #available(iOS 10.0, *) {

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in

            })

            UNUserNotificationCenter.current().delegate = self

            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {

            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

    //  MARK: - Firebase Connection Methods
    @objc func getFirebaseInstaceID(_ notification: Notification) {

        if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
            let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
            if !strFirebaseInstanceID.isEmpty {
                print("Firebase Instance ID - \(strFirebaseInstanceID)")
                setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)

                NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
            } else {
                setString(strValue: "", forKey: Default.firebaseInstanceID)
            }
        } else {
            setString(strValue: "", forKey: Default.firebaseInstanceID)
        }

        connectToFcm()
    }

    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
}
8
  • Can you please share the payload that you are sending? Commented Mar 23, 2017 at 7:14
  • For what OS you are facing this issue? Commented Mar 23, 2017 at 7:25
  • @Karthick I'm facing this issue for iOS 10.1 Commented Mar 23, 2017 at 7:27
  • Just seen your comment in one of the answers. Could you post a screenshot of a sample message that you're sending using the Notification Console? (edit out the sensitive details) Commented Mar 23, 2017 at 7:38
  • 2
    Dear @VaibhavJhaveri, we've rollback your changes to a version more in phase with community editorial choices. If you have concerns, I would suggest to re-read the help pages in general or the "how-to-ask" in particular. You may also search on Meta and eventually raise a question on Meta. Commented Nov 29, 2017 at 13:07

3 Answers 3

1

For iOS 10.*, you need to give push notification present option in completion handler of willPresent notification method list below. Try like this may be helpful.

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {    

        completionHandler([.alert, .badge, .sound])

}

Thanks.

Sign up to request clarification or add additional context in comments.

1 Comment

Tried. Didn't help
1

As you are sending push using FCM, try sending this payload to FCM for push.

{
  "to": "<REGISTRATION_TOKEN_HERE>",
  "notification": {
    "body": "Yipeee!!! I nailed it",
    "sound" : "default"
  },
  "data" : ""
}

6 Comments

I'm using Firebase Console to send notification
I have not tried sending push using console but i do it using googleapi's Using post request, url being https://gcm-http.googleapis.com/gcm/send and headers Authorization:key=yourKey Content-Type:application/json
@TechGeek_iOS https://gcm-http.googleapis.com/gcm/send is the GCM endpoint. Although both are still compatible, as much as possible for FCM, use https://fcm.googleapis.com/fcm/send. :)
Also, I noticed your format -- "to": "FCM_INSTANCE_ID/GCM_ID_GOES_HERE". It doesn't make sense to include the GCM_ID there (I'm not even sure what you mean by the GCM_ID.
FCM_INSTANCE_ID is FIRInstanceID.instanceID().token, generated for each device
|
0

I forgot to add this method

didReceiveRemoteNotification

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.