firebase iOS not receive push notifications - ios

I include google firebase in my app - create google account, create google app, upload APNS certifications (.pem and in work in another service), and send push notifications from console, and my app not receive it. In Firebase console i see status complete but Approximate number of devices is "-"
Of course I updated provisions profiles and APNS cert
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Register for remote notifications
if #available(iOS 8.0, *) {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Fallback
let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
application.registerForRemoteNotificationTypes(types)
}
FIRApp.configure()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
name: kFIRInstanceIDTokenRefreshNotification, object: nil)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
func tokenRefreshNotificaiton(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
User.sharedUser.googleUID = refreshedToken
}
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
print(userInfo)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
print(userInfo)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("ошибка")
print(error)
print(error.description)
}

The first thing I see is there's no call to connect to FIRMessaging. Try adding this to your AppDelegate:
func applicationDidBecomeActive(application: UIApplication) {
FIRMessaging.messaging().connectWithCompletion { error in
print(error)
}
}

Use the following code.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
if #available(iOS 10.0, *)
{
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert]) { (granted, error) in
if granted
{
//self.registerCategory()
}
}
// 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()
//Configuring Firebase
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)
return true
}
//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}
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()
}
func connectToFcm()
{
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil)
{
print("Unable to connect with FCM. \(error)")
}
else
{
print("Connected to FCM.")
}
}
}
func applicationDidBecomeActive(application: UIApplication)
{
connectToFcm()
}

You might be using Data or aps key in PUSH JSON which is used to send notifications to devices. It should work properly but in rare cases, it not works, even it'll give you success in fcm/send api but notification will not reach particular devices. This problem usually occurs in iOS devices.
A solution which worked for me is add notification key instead of Data.
{
"to" : "device token",
"notification":{
"body": "test",
"title": "test"
}
}
If you are sending from Backend OR you don't have access of Firebase console. Then you can test and send notification via POSTMAN also. But you must have SERVER KEY, which can be got from Firebase console under Cloud Messaging settings.
API: https://fcm.googleapis.com/fcm/send
Method: POST
Headers:
"Content-Type"=application/json
"Authorization"="key=YOUR SERVER KEY" //You must add key= above the server key.
{
"to" : "your device token",
"notification":{
"body": "test",
"title": "test"
}
}
ANOTHER DETAILED AND FULL PAYLOAD IF YOU NEED TO SEE WHAT WE CAN SEND IN FIREBASE NOTIFICATION:
{
"to":"device token",
"notification":{
"data":{
"avatar":"",
"body":"",
"key_notification":"0",
"type_notification":"1",
"deviceToken":"device token",
"badge":1,
"message":"your text"
},
"text":"your text",
"sound":"sound.caf",
"badge":21
},
"priority":"high"
}

Related

Push Notification Not Working iOS Using FCM

I have implemented FCM. There is no error showing. Token successfully generated. But no notification coming into the device.
I followed the google documentations.
Here is my AppDelegate class
import Foundation
import UIKit
import Firebase
//https://github.com/firebase/quickstart-ios/blob/5694c29ac5a8dcc672ec13f55f0ab74a6b9af11e/messaging/MessagingExampleSwift/AppDelegate.swift#L40-L55
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
// 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 })
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict:[String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
}
didReceiveRegistrationToken delegate method callings twice
Here is my Capabilities
I tried send notification from firebase cloud messaging option, but not coming to any Push in device.
I also tried from postman. Here is my payload and output
I have uploaded the APNS certificate in firebabse .
I tried into main project and its not working.
Then I tried to fresh implement into a dummy project its also not working.
Here is my source code. You may check into this.
https://www.dropbox.com/s/22wojqv5u3vwjzt/Swift%20UI%20Push%20Notification.zip?dl=0
I think the payload is different for APNS.From the document I found that the following is the format for FCM payload in APNS
{
"message": {
"token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "This is an FCM notification that displays an image.!",
"title" : "FCM Notification",
},
"apns": {
"payload": {
"aps": {
"mutable-content": 1
}
},
"fcm_options": {
"image": "url-to-image"
}
}
}
}
You can add all the UNUserNotificationCenterDelegate method along with completionHandler([.alert, .badge, .sound]).

Firebase FCM not working initially but works after 3-4 times if the app is opened

I am new to Firebase FCM Integration and i am facing some issues. When the app is installed for first time i don't receive Push Notification but if i open and close app for few times and then send push notification from Firebase i am receiving notification without any change in client or server code. Can anyone help me out on this?
I have attached my appdelegate code below
import UIKit
import Firebase
import UserNotifications
import FirebaseMessaging
import FirebaseInstanceID
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
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: { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
return true
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
UIApplication.shared.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// I have tried both method but none worked and i also tried MessagingAPNSTokenType.sandbox and prod
// Method 1: Messaging.messaging().apnsToken = deviceToken
// Method 2:
Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
}
}
Thanks in advance
I have the same issue as you have and there is a known issue where the FCM token is not always being associated with the APNs device token if UIApplication.shared.registerForRemoteNotifications() is not called early enough.
According to this GitHub thread this issue has already been fixed in the FirebaseInstanceID SDK, and should be coming out soon.
In the meantime, you can:
Lock your FirebaseInstanceID pod to 2.0.0 in your Podfile, or
Ensure you're calling UIApplication.shared.registerForRemoteNotifications() on app start, ideally before FirebaseApp.configure().
Update:
I just made some additional tests and I noticed that this is a bit random of when this will work. For some devices it worked immediately for some not. For some devices Single Token push worked and not User Segment. I managed to make it work so that you at least either get Single Token push or User Segment by adding the following:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in
})
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
Messaging.messaging().delegate = self
application.registerForRemoteNotifications()
print("::: registerForRemoteNotifications iOS 10")
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
print("::: registerUserNotificationSettings iOS 9")
}
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
if let refreshedToken = InstanceID.instanceID().token() {
print("::: InstanceID token: \(refreshedToken)")
}
NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
if let refreshedToken = InstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
}
The thing is that it won´t work if you don´t access the didRegisterForRemoteNotificationsWithDeviceToken function.
Firebase FCM, it takes sometime to generate its first token. After getting this token you will start receiving push notification. Check these out. It will be clear for sure:
Check this answer
AppDelegate implementation with FCM
Hope this helps.
Update your appdelegate by this
import FirebaseCore
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.fcmInitialSetup(application)
return true
}
func fcmInitialSetup(_ application: UIApplication){
// [START register_for_notifications]
if #available(iOS 10.0, *) {
let uns: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(uns)
application.registerForRemoteNotifications()
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
if let token = FIRInstanceID.instanceID().token() {
sendTokenToServer(token)
}
}
func sendTokenToServer(_ currentToken: String) {
print("sendTokenToServer() Token: \(currentToken)")
// Send token to server ONLY IF NECESSARY
print("InstanceID token: \(currentToken)")
self.token = currentToken
UserDefaults.standard.set(self.token, forKey: "token")
UserDefaults.standard.synchronize()
if self.token != nil{
let userInfo = ["token": self.token]
NotificationCenter.default.post(
name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
}
}
// NOTE: Need to use this when swizzling is disabled
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var tokenString = ""
for i in 0..<deviceToken.count {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
print("Device Token:", tokenString)
print("FIRInstanceID.instanceID().token() Token:", FIRInstanceID.instanceID().token())
if let tokenData = FIRInstanceID.instanceID().token(){
UserDefaults.standard.set(tokenData, forKey: "token")
UserDefaults.standard.synchronize()
let userInfo = ["token": tokenData]
}
}
func tokenRefreshNotification(_ notification: Notification) {
// NOTE: It can be nil here
// print("Token:\(FIRInstanceID.instanceID().token()!)")
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
UserDefaults.standard.set(refreshedToken, forKey: "token")
UserDefaults.standard.synchronize()
print("update now \(self.token)")
if self.token != nil{
let userInfo = ["token": self.token]
NotificationCenter.default.post(
name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
}
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
print("Within open URL")
return true
}
// [START receive_apns_token_error]
func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
error: Error ) {
print("Registration for remote notification failed with error: \(error.localizedDescription)")
// [END receive_apns_token_error]
let userInfo = ["error": error.localizedDescription]
NotificationCenter.default.post(
name: Notification.Name(rawValue: rkey), object: nil, userInfo: userInfo)
}
func registrationHandler(_ token: String!, error: NSError!) {
if (token != nil) {
self.token = token!
print("Registration Token: \(self.token)")
UserDefaults.standard.set(self.token, forKey: "token")
UserDefaults.standard.synchronize()
let userInfo = ["token": self.token]
NotificationCenter.default.post(
name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
} else {
print("Registration to GCM failed with error: \(error.localizedDescription)")
let userInfo = ["error": error.localizedDescription]
NotificationCenter.default.post(
name: Notification.Name(rawValue: self.rkey), object: nil, userInfo: userInfo)
}
}
func registerForPushNotifications(_ application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(
types: [.badge, .sound, .alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != UIUserNotificationType() {
application.registerForRemoteNotifications()
}
}
// [START receive_message]
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. add Toast
print(userInfo);
print(application.keyWindow?.visibleViewController() ?? "")
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
}
// [END receive_message]
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
// FIRMessaging.messaging().disconnect()
// print("Disconnected from FCM.")
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
}
}
// [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,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print message ID. add Toast
// Print full message.
print("%#", userInfo)
// Print full message.
print("%#", userInfo)
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}
NotificationCenter.default.addObserver(self selector:#selector(self.getFcmToken), name: .firInstanceIDTokenRefresh,
object: nil)
put this in application did finsih launching method
and make a function
func getFcmToken(notification: NSNotification) {
guard let contents = FIRInstanceID.instanceID().token()
else {
return
}
print("InstanceID token: \(contents)")
if let token = FIRInstanceID.instanceID().token(){
print(token)
}

dont get notification when my app is kill

when my app is in background or foreground i can get notification but when my app is kill . i can't get notification .
i use of fcm ...
this is my payload that call via postman .
{
"registration_ids":
["...."],
"notification":{
"sound":"default",
"title":"testNotif",
"body":"welcome in the shop Apple owner"
}
}
This is my appdelegate:
import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_,_ 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()
FIRApp.configure()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.prod)
}
func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
if let refreshedToken = FIRInstanceID.instanceID().token() {
Common.tokenFCM = refreshedToken
print("InstanceID token: \(refreshedToken)")
}
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
private func userNotificationCenter(center: UNUserNotificationCenter,
willPresentNotification notification: UNNotification,
withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("<<<<<<< %#", userInfo)
}
}
extension AppDelegate : FIRMessagingDelegate {
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(">>>>> %#", remoteMessage.appData)
}
}
Hi use this json format
{
"registration_ids":
["...."],
"priority":"high",
"notification":{
"sound":"default",
"title":"testNotif",
"body":"welcome in the shop Apple owner"
}
}
There is a problem with priority in this case. If you are not setting it means at normal priority, it may have chance that notification not appears immediately. If you are setting priority to high that means you receive notification immediately. may be because of the way iOS bundles notifications handles it like that.
So what does High Priority do: (Instant messaging)
Attempts to deliver messages immediately and simply makes a network connection with your app server as soon as notification appears to your device. But one more thing you need to consider is power consumption of device. High priority consume more battery than normal one.
For more info and details, you can check Firebase: Setting the priority of a message and Apple Doc

Swift 3 - Firebase Push Notification, How can I do?

I do like below in Swift 2. But It's not working in Swift 3. How Can I provide this? If someone explain this It would be great.
didFinishLaunchingWithOptions
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
application.registerForRemoteNotifications()
and
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Meesage ID \(userInfo["gcm_message_id"]!)")
print(userInfo)
}
I can do simple local notification but, I couldn't remote push notification from Firebase.
I tried
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Alert, .Badge, .Sound]) { (success, error:NSError?) in
if success {
print("Notification access true!")
application.registerForRemoteNotifications()
}
else {
print(error?.localizedDescription)
}
}
and
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Meesage ID \(userInfo["gcm_message_id"]!)")
print(userInfo)
}
still doesn't work.
The AppDelegate method names have changed a little and UserNotifications framework has been introduced. You must use this framework for notifications in iOS 10 and above as the other methods are being deprecated.
import UserNotifications
...
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> ()) {
print("Message ID \(userInfo["gcm.message_id"]!)")
print(userInfo)
}
...
}
Registering for Push Notifications in Xcode 8/Swift 3.0?
It is very important to remember that there may be different devices that run different versions of the iOS, and they may have different notification capabilities. I understand that the previous answer does point in the right direction.
We need to import FirebaseInstanceID, if we are to receive instance, or event based notifications. Such notifications are like the ones that pop-up when someone retweets our post, or likes a post, or a message notification.
However, if someone is looking for the complete code that goes into the didFinishLaunchingWithOptions function in AppDelegate, here it is:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
authOptions, completionHandler: {_,_ in })
} else {
// Fallback on earlier versions
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification,
object: nil)
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// This is required if you are receiving a notification message while your app is in the background, which is the most common case!!
print("Message ID: \(userInfo["gcm.message_id"]!)")
print("%#", userInfo)
}
func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
This is what works for me Xcode 8, Swift 3.
Inside didFinishLaunchingwithOptions func in AppDelegate.swift
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {granted, error in
print(granted)
})
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FIRApp.configure()
// [START set_messaging_delegate]
FIRMessaging.messaging().remoteMessageDelegate = self
// [END set_messaging_delegate]
And the Delegates required to receive notifications from firebase:
#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.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
let aps = userInfo["aps"] as! [String: Any]
let notificationMessage = aps["alert"] as! String // processed content from notificaton
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}

Firebase Notification not working on Testflight

I have created app with notification. When i send notification on developer mode then i get notifications. but when i send on release mod i don't get anything. I read that i should change certificate to product certificat. But it doesn't helped. here is my appdelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
let notificationTypes : UIUserNotificationType = [.alert, .badge, .sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)
return true
}
private func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
FIRMessaging.messaging().subscribe(toTopic: "/topics/main")
}
private func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.prod)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo["gcm.message_id"]!)
print(userInfo)
}
func application(_ application: UIApplication, dirtings: UIUserNotificationSettings)
{
UIApplication.shared.registerForRemoteNotifications()
}
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()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
private func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
Just went through this,
I turned push off and deleted the certs from apple dev center and created them all over again and this made everything work as it should.
I also had this line of code set to,
FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.sandbox)
I will change it to .prod when I push to the app store.
I found solution. problem was with prod certificate. i forget to add prod cetificate to firebase.

Resources