5

I am struggling to display my push notifications that I am sending to my device from the FCM notification console. I can see the device is receiving the notification because I can see the message I send "test8"

Connected to FCM.
%@ [AnyHashable("notification"): {
    body = test8;
    e = 1;
},

But it does not matter if my app is in the foreground or background I don't get the notification displayed.

I have added "Required background modes - App downloads content in response to push notifications" to the info.plist. My certificates are correct and I have no issue generating a token. My app is receiving the notifications but just not displaying them.

import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
            UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
                authOptions,
                completionHandler: {_,_ in })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.currentNotificationCenter().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

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

        application.registerForRemoteNotifications()

        // [END register_for_notifications]

        FIRApp.configure()

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

        return true
    }

    // [START receive_message]
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (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

        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }
    // [END receive_message]

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

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

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

    func applicationDidBecomeActive(application: UIApplication) {
        connectToFcm()
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }
    // [END disconnect_from_fcm]
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(center: UNUserNotificationCenter,
                                willPresentNotification notification: UNNotification,
                                withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        // Print full message.
        print("%@", userInfo)
    }
}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}
// [END ios_10_message_handling]

I having been trying to research and solve this issue on my own but I am having issues. Any help or suggestions would be greatly appreciated.

Alexey
  • 1,177
  • 2
  • 14
  • 23
Paul_D
  • 255
  • 2
  • 8
  • 21
  • Did u solve ur issue, I am not receiving notifications in Xcode 8.1 swift 2.3.since couple of days i am trying from server side i am receiving and also when i send firebase console i am getting .Please can u help me . – Uma Madhavi Dec 18 '16 at 16:19

3 Answers3

8

Inside method didRegisterForRemoteNotificationsWithDeviceToken, add the following code:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

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

    print("tokenString: \(tokenString)")
}

And do not forget to enable Push Notifications inside Capabilities.

Gustavo Barbosa
  • 580
  • 3
  • 13
  • i added the following because I am using swift syntax but it did not solve the issue I am having. I do appreciate the suggestion though. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox) } – Paul_D Sep 27 '16 at 18:24
  • 1
    @Paul_D Add this line to your Info.plist file: FirebaseAppDelegateProxyEnabled and set the Boolean value to NO – Gustavo Barbosa Sep 27 '16 at 18:29
  • Thank you for the help Gustavo. I am still struggling I am getting the following error... Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)". I am getting the notifications just not displaying them. I am searching google and trying everything I can to resolve this issue. I know I have correctly uploaded my .p12 certificated to the Firebase console under project settings, and the under cloud messaging. Push notifications and (background mode --> remote notifications) are both enabled. – Paul_D Sep 27 '16 at 19:56
  • 1
    @Paul_D yes Paul, it's a little difficult to help in here because you need to follow several steps. I did a video with a tutorial, but it's in portuguese and it's not in the web yet. But did you import the JSON generated by Firebase in your application? – Gustavo Barbosa Sep 28 '16 at 11:32
  • Is it possible to upload a screenshot of your Info.plist? And your .entitlements file? – Gustavo Barbosa Sep 28 '16 at 11:44
  • 1
    Gustavo I followed your instructions and the notifications are now working. I had to follow you direction and then I uninstalled the app from my device, cleaned the project, rebuild and then reinstalled it on my phone. I am now able to receive notifications while my app is running in the foreground and background. Thank you for your help. I really appreciate it a lot. – Paul_D Sep 28 '16 at 12:26
  • @Paul_D Glad to help :) – Gustavo Barbosa Sep 28 '16 at 12:38
  • 2
    Anyone converted this into Swift 3 code? error: Cannot invoke initializer for type 'UnsafePointer' with an argument list of type '(UnsafeRawPointer)' -so there is a whole new way for UnsafeRawPointer – Jón Andri Sep 28 '16 at 23:29
  • Yes, it is working, BUT: there is a small problem in the original code: missing application.registerForRemoteNotifications() in didFinishLaunchingWithOptions(). It should be ALSO called for iOS 10. – Alexey Oct 11 '16 at 10:58
  • @GustavoBarbosa.. I don't know what wrong with my code http://stackoverflow.com/q/41198651/5362916 I am not receiving notifications in Xcode 8.1 swift 2.3.since couple of days i am trying from server side i am receiving and also when i send firebase console i am getting.These messages are not getting from top .Please can u guide me – Uma Madhavi Dec 18 '16 at 16:24
3

You need to move

 application.registerForRemoteNotifications()

it should not be inside the else.

// [START register_for_notifications]
    if #available(iOS 10.0, *) {
        let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
            authOptions,
            completionHandler: {_,_ in })

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self

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

application.registerForRemoteNotifications()

See following commit in Firebase

Collinizer
  • 201
  • 1
  • 6
2

For me it was the missing entitlements file, so in the Capabilities of your project, you have to click fix issue. Xcode will setup the file for you.

enter image description here

AITAALI_ABDERRAHMANE
  • 2,499
  • 1
  • 26
  • 31