简体   繁体   中英

Firebase notifications (only data) not receiving in Foreground

Hey everyone I've reading some problems that people have with Firebase and iOS notifications but seems that anybody is having the same issue.

For now I'm talking on FOREGROUND app state:

App receive the notification ever that have the parameter notification for exemple like this:

let notificationsParameters:[String:AnyObject] = [
        "to": "iphoneID",
        "content-available":true,
        "priority":"high",
// "notification" : [
//                "body" : "great match!",
//                "title" : "Portugal vs. Denmark",
//                "icon" : "myicon"
//            ],
        "data" : [
            "Nick" : "Mario",
            "Room" : "PortugalVSDenmark"
        ]
    ]

but once I removed the notification part app doesn't receive nothing, even keeping in foreground where as I see everyone should receive the notification.

I added priority high to receiving even closed/background and content-available, that I read is suppoused to solve my problem but is not the case.

Here you have the involved code:

APP DELEGATE

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



        GMSServices.provideAPIKey(Constants.GoogleMaps.APIKey)
        FIRApp.configure()


        /* NOTFICATIONS */

        let notificationsType:UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
        let notificationSettings = UIUserNotificationSettings(forTypes: notificationsType, categories: nil)
        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)), name: kFIRInstanceIDTokenRefreshNotification, object: nil)


        return true
    }

NOTIFICATIONS (IN APP DELEGATE)

As I understand this is what is suppouse that I will receive the data of the notification

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)
    }

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

        connectToFCM()
    }

    func connectToFCM() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("GMS ERROR: \(error)")
            }
            else {
                print("Connected to GMS")
            }
        }
    }

CALL TO FIREBASE NOTIFICATIONS

func sendNotification() {

        let notificationsParameters:[String:AnyObject] = [
            "to": "iphoneID",
            "content-available":true,
            "priority":"high",
            //            "notification" : [
            //                "body" : "great match!",
            //                "title" : "Portugal vs. Denmark",
            //                "icon" : "myicon"
            //            ],
            "data" : [
                "Nick" : "Mario",
                "Room" : "PortugalVSDenmark"
            ]
        ]


        let URL = NSURL(string: "https://fcm.googleapis.com/fcm/send")!
        let URLRequest = NSMutableURLRequest(URL: URL)

        URLRequest.HTTPMethod = "POST"

        URLRequest.setValue("key=\(Constants.Firebase.NotificationsKey)", forHTTPHeaderField: "Authorization")
        URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let encoding = Alamofire.ParameterEncoding.JSON

        let encoded = encoding.encode(URLRequest, parameters: (notificationsParameters)).0
        Alamofire.request(encoded)
    }

Any further information you need just let me know!

You were on the right track, but need an underscore instead of hyphen in the content_available parameter. No need to use the notification object if you want a data only (silent) notification using FCM.

Eg, in your FCM send request body:

{
    "to": "iPhoneID",
    "content_available": true,
    "priority": "high",
    "data": {
        "nick": "mario",
        "room": "PortugalVSDenmark"
    }
}

For those who have the same problem that me, one solution is setting notification parameters like this:

let notificationsParameters:[String:AnyObject] = [
            "to": "iphoneID",
            "content-available":true,
            "priority":"high",
           "notification" : [
               "sound" : " "
           ],
            "data" : [
                "Nick" : "Mario",
                "Room" : "PortugalVSDenmark"
            ]
        ]

You won't receive the notification when app is killed but you will be able to receive only data notification when is in foreground and background, good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM