8

I am following sampler project provided by firebase. Firebase Cloud Messaging sammple

My app delegate is

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
import FirebaseInstanceID

//add firebase code app delegate code

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"


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


    // 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()

    // [END register_for_notifications]
    FirebaseApp.configure()

    // [START set_messaging_delegate]
    Messaging.messaging().delegate = self
    // [END set_messaging_delegate]

    return true

}

// [START receive_message]
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.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(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
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]


func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")

    // With swizzling disabled you must set the APNs token here.
    InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.sandbox)

}


}


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

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert,.badge,.sound])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
}
}
// [END ios_10_message_handling]

extension AppDelegate : MessagingDelegate {

// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {

    print("Firebase registration token: \(fcmToken)")

    print(fcmToken)

    resgisterNotificationToken(fcmToken: fcmToken)

}
// [END refresh_token]

func application(received remoteMessage: MessagingRemoteMessage) {

    //get called when sending notification from POSTMAN and when app is open

    print("%@", remoteMessage.appData)

    print("%@", remoteMessage)

}


func resgisterNotificationToken(fcmToken:String){

    //let deviceId = UIDevice.current.identifierForVendor!.uuidString

    //let parameters = ["OTY": AppConstants.init().OS_TYPE,"REGID": fcmToken] as Dictionary<String, String>



}

}

I can receive notification which was sent from firebase console. i have upgraded my firebase library to latest 3.0 something.

also i am getting following warning. 'InstanceIDAPNSTokenType' is deprecated: Use FIRMessaging's APNSToken property instead.

kindly provide solution with code and give me server request structure so that i can test it from postman.

Thanks in advance.

user3066829
  • 157
  • 1
  • 1
  • 12

2 Answers2

12

Can you try setting the apn token like this:

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

FIRInstanceID setAPNSToken

Set APNS token for the application. This APNS token will be used to register with Firebase Messaging using token or tokenWithAuthorizedEntity:scope:options:handler. If the token type is set to FIRInstanceIDAPNSTokenTypeUnknown InstanceID will read the provisioning profile to find out the token type.

Firebase API reference

It's working for me!

EDIT:

With Firebase version 4.0.0 the way to do it has changed:

Messaging.messaging()
    .setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)

FIRMessaging API reference

rihhot
  • 121
  • 6
  • FIRInstanceID change to InstanceID and FIRInstanceIDAPNSTokenType change to InstanceIDAPNSTokenType ..i have upgraded firebase libraries to latest.. – user3066829 May 23 '17 at 10:24
  • Are you using then iOS SDK 4.0.0? This was released at May 17 so I'm not working with this version for the moment. Can you try using: `Messaging.messaging().apnsToken = deviceToken`. It maybe will resolve your problem. [Look at Firebase API reference](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/APNS) – rihhot May 23 '17 at 10:38
  • i think this is a correct way to do it :Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown) – user3066829 May 23 '17 at 11:21
  • Hey folks, as the author of those changes, the preferred way is for you to just use the property setter, like `Messaging.messaging().apnsToken deviceToken`. The `setAPNSToken(_,type:)` is there for legacy reasons. – Rizwan Sattar May 23 '17 at 15:42
  • Use of unresolved identifier 'InstanceIDAPNSTokenType' – Vishal Vaghasiya Nov 01 '18 at 11:50
9

I've just updated the Github sample app to reflect the API changes. Sorry about that. I think some of the changes slipped through. The preferred way to set the APNs token (if you have disabled swizzling) is now:

Messaging.messaging().apnsToken = deviceToken

The old method, setAPNSToken:type: was causing more confusion because if the type was included and it did not match the type of build, the FCM token would not work. If you do need to use the old method, I'd recommend using the 'Unknown' enum, which will do an automatic check.

Your question title mentioned that you're not receiving data messages and the new sample change should show that. The way to receive data messages is:

  1. Enable the direct channel by setting: Messaging.messaging().shouldEstablishDirectChannel = true

  2. Implement the FIRMessagingDelegate and the messaging:didReceiveRemoteMessage method.

Another sample app you can look at is part of the open-source FCM repo here.

Rizwan Sattar
  • 1,618
  • 1
  • 15
  • 23
  • I tried - Messaging.messaging().apnsToken = deviceToken - but it wanted me to recast it as Data instead of the new NSData in the FB documentation – Erik Grosskurth May 31 '17 at 18:16
  • 1
    @ErikGrosskurth hmm, can you point me to the documentation? Perhaps the docs need to be updated. You're using Swift, right? – Rizwan Sattar May 31 '17 at 20:03
  • https://stackoverflow.com/questions/44294144/push-notifications-not-working-in-firebase-4-0 – Erik Grosskurth May 31 '17 at 20:30
  • i am able to receive data notification but i am not getting the notification banner as well as i am not getting the notification when my app is in background mode, once i open my app i can receive notification but i am not getting banner for that. – user3066829 Jul 05 '17 at 12:51
  • @user3066829 Can you show me what kind of payload you are sending via the FCM HTTP API? Are you including a "notification" key in your JSON payload? – Rizwan Sattar Jul 06 '17 at 23:02
  • to:reg_id, data.msg:this is msg, data.type:2, data.id:190 @RizwanSattar – user3066829 Jul 10 '17 at 07:40
  • i am trying to send it using postman...or u can suggest me command prompt script with data payload – user3066829 Jul 10 '17 at 07:43
  • @user3066829, apologies for the late response, but the issue here is that you’re sending the notification only using a “data” key. You’ll need to include a “notification” key in the payload [with the approprate sub-keys (title, body, etc.)](https://firebase.google.com/docs/cloud-messaging/http-server-ref). Hope that helps! – Rizwan Sattar Jul 31 '17 at 18:07