16
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    registerForPushNotifications(application)
    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter
     .defaultCenter()
     .addObserver(self, selector: #selector(AppDelegate.tokenRefreshNotificaiton),
                                                     name: kFIRInstanceIDTokenRefreshNotification, object: nil)

    // Override point for customization after application launch.
    return true
  }

func registerForPushNotifications(application: UIApplication) {
      let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
      application.registerUserNotificationSettings(settings)
      application.registerForRemoteNotifications()
  }


  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                   fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    print("===== didReceiveRemoteNotification ===== %@", userInfo)
  }


 func tokenRefreshNotificaiton(notification: NSNotification) {
    let refreshedToken = FIRInstanceID.instanceID().token()!
    print("InstanceID token: \(refreshedToken)")

    // Connect to FCM since connection may have failed when attempted before having a token.
     connectToFcm()
  }

  func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
      if (error != nil) {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }

Also to done in Info.plist FirebaseAppDelegateProxyEnabled = NO

I don't know for now but I got the print(...) in didReceiveRemoteNotification but don't get the popup. I send the message from Firebase -> Console -> Notification -> Single device and copy here the token which I got from xCode Console -> func tokenRefreshNotificaiton

Get the next in console, but don't get popup

<FIRAnalytics/INFO> Firebase Analytics enabled
InstanceID token: TOKEN_ID
Connected to FCM.
===== didReceiveRemoteNotification ===== %@ [notification: {
    body = test;
    e = 1;
}, collapse_key: com.pf.app, from: 178653764278]

Also app configurations enter image description here

Svitlana
  • 2,938
  • 1
  • 29
  • 38
  • Possible solution :) http://stackoverflow.com/questions/37538330/fcm-notification-is-not-working-in-ios/38093732#38093732 – DiAvisoo Jun 29 '16 at 08:35
  • I was having the same issue.. Try this out.. http://stackoverflow.com/questions/37929979/firebase-remote-notifications-not-receiving – V1P3R Aug 28 '16 at 02:03

6 Answers6

11

set the following code in AppDelegate.m

   - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    // for development 
        [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];

    // for production 
   //     [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];


    }
  • 1
    Hi Alaa, welcome to StackOverflow. I've suggested an edit to your answer to add in code formatting (4 indented spaces) to make it easier to read. Would you mind also editing your answer to explain _why_ this solves the problem? Thank you! – Tim Malone Jul 17 '16 at 06:55
  • If the token type is set to FIRInstanceIDAPNSTokenTypeUnknown InstanceID will read the provisioning profile to find out the token type. From the docs: https://firebase.google.com/docs/reference/ios/firebaseinstanceid/interface_f_i_r_instance_i_d#a7cd9dde64e899e05a27397d3ee3fb398 – Rabs G Sep 06 '16 at 14:22
  • 2
    you saved my day man, I was struggling why my notification was not working in background mode, but after adding this it started working. But this was not found in firebase messaging https://github.com/firebase/quickstart-ios/blob/master/messaging/FCM/AppDelegate.m sample code which is strange – Antarix Sep 29 '16 at 11:57
  • I integrate this code but not working.when i send message from firebase console and add device token i am getting error Invalid registration token. Check the token format. – Krutarth Patel Dec 31 '16 at 10:28
  • `FIRInstanceIDAPNSTokenTypeSandbox` is `The APNS token type for the app. If the token type is set to UNKNOWN InstanceID will implicitly try to figure out what the actual token type is from the provisioning profile.` I got that problem when using Match – Nike Kov Feb 21 '17 at 13:42
1

I'm guessing your app is in the foreground when testing. When your app is in the foreground no visible notification is triggered, instead you receive the callback to didReceiveRemoteNotification. See the documentation for more info.

To verify, put your app in the background and try sending the push notification again.

AdamK
  • 21,199
  • 5
  • 42
  • 58
  • Sorry, I need to clarify. When the app goes into background, during first 30 seconds it isn't fall asleep yet, so for this reason I still get didReceiveRemoteNotification calls. After no calls. – Svitlana Jun 08 '16 at 19:20
  • Ah in that case I agree my answer will not help and I'm not sure what the problem might be. Sorry! – AdamK Jun 10 '16 at 10:42
0

I have same configuration you have and it works like AdamK said. (While in background mode, notification appears.) Also check your certificates.

wseries
  • 490
  • 5
  • 14
  • Check this video, https://www.youtube.com/watch?v=VpbNFIY1qJ0 time 13:45. They said that if you set Info.plist FirebaseAppDelegateProxyEnabled to NO you should call "setAPNSToken" and "appDidReceiveMessage" – wseries Jun 09 '16 at 00:18
0

First check with Firebase Notification Console to see if the notification is sending or not. If it is success, then the problem is in the code side; otherwise, check what error is coming in Firebase. If you receive error message as APNs missing, you need to check with development/production .p12 file in Project Setting->Cloud Messaging tab.

Pang
  • 9,564
  • 146
  • 81
  • 122
Kavin Kumar Arumugam
  • 1,792
  • 3
  • 28
  • 47
0

Just use this function in your app delegate sandbox for development prod for prodction

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
}
Gowtham Sooryaraj
  • 3,639
  • 3
  • 13
  • 22
0

Are you using https://pushtry.com for test the FCM notification? then don't use because I have lots of issue with this website for testing notification some time it working and some times not. it's not giving consistence result and it may be effect in FCM flow and totally block the receiving notifications.

I recommended to use https://fcm.snayak.dev for test the notification.

kuldip bhalodiya
  • 992
  • 7
  • 11