iOS FCM not getting push notifications - ios

Since i updated to swift 3, FCM doesn't work.
Push Notifications are enabled in Capabilities and Certificates are updated on Firebase console.
Btw, fcm on android app works just fine, and it was working on ios but after update on swift 3 and new firebase libraries, it doesn't.
AppDelegate.swift:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let notificationCenter = NotificationCenter.default
var connectedToFcm: Bool = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
FIRApp.configure()
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
disconnectFromFcm()
}
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("REGISTRED")
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .unknown)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
error: Error ) {
print("Registration for remote notification failed with error: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
func tokenRefreshNotification(_ notification: Notification) {
let refreshedToken = FIRInstanceID.instanceID().token()
if refreshedToken != nil {
print("InstanceID token: \(refreshedToken!)")
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
}
func connectToFcm() {
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
if connectedToFcm == false {
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
self.connectedToFcm = false
print("Unable to connect with FCM. \(error)")
} else {
self.connectedToFcm = true
print("Connected to FCM.")
self.sendTokenToServer()
}
}
return
}
}
func sendTokenToServer() {
let fcmToken = FIRInstanceID.instanceID().token()
if self.sharedUser.getToken().characters.count == 0 || fcmToken == nil {
return
}
let params = [
"reg_id": fcmToken!,
"dev_id": Config().devId
]
Alamofire.request(Config().fcmUrl, method: .post, parameters: params, encoding: JSONEncoding.default, headers: Config().apiHeaders)
.validate()
.responseJSON { response in
if response.result.isSuccess {
print("FCM token send to app server")
}
}
}
func disconnectFromFcm() {
FIRMessaging.messaging().disconnect()
connectedToFcm = false
print("Disconnected to FCM")
}
}
Log:
2016-12-22 09:26:34.921315 app[6198:1607437] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist
2016-12-22 09:26:35.056527 app[6198:1607490] [Firebase/Core][I-COR000001] Configuring the default app.
2016-12-22 09:26:35.057: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-12-22 09:26:35.057 app[6198] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-12-22 09:26:35.060: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-12-22 09:26:35.064: <FIRMessaging/INFO> FIRMessaging library version 1.2.0
2016-12-22 09:26:35.065598 app[6198:1607526] <FIRAnalytics/INFO> Firebase Analytics v.3501000 started
2016-12-22 09:26:35.067: <FIRMessaging/WARNING> FIRMessaging AppDelegate proxy enabled, will swizzle app delegate remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-12-22 09:26:35.067 app[6198:] <FIRAnalytics/INFO> Firebase Analytics v.3501000 started
2016-12-22 09:26:35.069638 app[6198:1607526] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2016-12-22 09:26:35.069 app[6198:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2016-12-22 09:26:35.073182 app[6198:1607488] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-12-22 09:26:35.073 app[6198:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-12-22 09:26:35.181355 app[6198:1607488] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly.
2016-12-22 09:26:35.181 app[6198:] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly.
2016-12-22 09:26:35.198981 app[6198:1607490] <FIRAnalytics/INFO> Firebase Analytics enabled
2016-12-22 09:26:35.199 app[6198:] <FIRAnalytics/INFO> Firebase Analytics enabled
2016-12-22 09:26:35.285: <FIRInstanceID/WARNING> APNS Environment in profile: development
REGISTRED
2016-12-22 09:26:35.387693 app[6198:1607489] [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-22 09:26:35.387 app[6198] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
Connected to FCM.
FCM token send to app server
I made prints to check if app gets token, and it does. Also, token is sent to server and i checked there if it is ok and if server is sending push.

I have faced same issue with iOS FCM integration I have solved it by using latest code for push notification in iOS 10.
You need to check the OS version of the device and segregate relevant codes.
if #available(iOS 10, *)
{
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}else
{
// Register for remote notifications
if #available(iOS 8.0, *) {
// [START register_for_notifications]
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
// [END register_for_notifications]
} else {
// Fallback
let types: UIRemoteNotificationType = [.alert, .badge, .sound]
application.registerForRemoteNotifications(matching: types)
}
}
Put this code in a function and call it from did finish launching also comment your code.
Do let me know if you still have any issues.
Important :- import UserNotifications
Delegate :-
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings)
{
/**
Allow device to register for remote notification.
*/
UIApplication.shared.registerForRemoteNotifications()
FIRMessaging.messaging().subscribe(toTopic: "/topics/test")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
/**
Send device token to firebase to get the FCM token for pushnotification from firebase.
*/
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
}

Related

FireBase Remote notifications giving APS error when already implemented

I'm pulling my hair out because I've triple checked and the following is True:
App delegate is setup (and now bloated)
APNs have been created signed and uploaded to apple downloaded keyed and uploaded to google
App has remote notifications toggled.
here is the app delegate:
import SwiftUI
import AVKit
import UIKit
import AVFoundation
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.playback)
} catch {
print("Audio session failed")
}
FirebaseApp.configure()
application.registerForRemoteNotifications()
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)
}
Messaging.messaging().delegate = self
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {granted, error in
print("Permission granted: \(granted)")
}
UNUserNotificationCenter.current().delegate = self
application.registerForRemoteNotifications()
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("FCM Token Is: \(fcmToken)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Token is: \(deviceToken)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Error is \(error)")
}
// MARK: - UISceneSession
func application(_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication,
didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
And the error log:
2020-10-07 12:25:57.235303-0500 Project[1428:310502] 6.34.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging
to ensure proper integration.
2020-10-07 12:25:57.249142-0500 Project[1428:310493] 6.34.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60900000 started
2020-10-07 12:25:57.249750-0500 Project[1428:310493] 6.34.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
Error is Error Domain=NSCocoaErrorDomain Code=3000 "no valid “aps-environment” entitlement string found for application" UserInfo={NSLocalizedDescription=no valid “aps-environment” entitlement string found for application}
2020-10-07 12:25:57.343208-0500 Project[1428:310500] 6.34.0 - [Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: no valid “aps-environment” entitlement string found for application
2020-10-07 12:25:57.350290-0500 Project[1428:310500] Metal API Validation Enabled
2020-10-07 12:25:57.476988-0500 Project[1428:310502] 6.34.0 - [Firebase/Analytics][I-ACS800023] No pending snapshot to activate. SDK name: app_measurement
2020-10-07 12:25:57.477541-0500 Project[1428:310502] 6.34.0 - [Firebase/Analytics][I-ACS023012] Analytics collection enabled
2020-10-07 12:25:57.477668-0500 Project[1428:310502] 6.34.0 - [Firebase/Analytics][I-ACS023220] Analytics screen reporting is enabled. Call +[FIRAnalytics logEventWithName:FIREventScreenView parameters:] to log a screen view event. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO (boolean) in the Info.plist
a simple update to Xcode 12.2 (beta 2) Command lines fixed the issue for whatever reason
I face with the same issue and after a few hours of research, I found the answer for my case.
In Target at Build Setting, find the key "CODE_SIGN_ENTITLEMENTS" and point it to the ".entitlements" file.

Push Notifications not working in Firebase 4.0

I updated my pods today to the new Firebase 4.0. I went through the suggested changes and grabbed code from the Github example. I will be honest I am at a loss, I take the FCM Token and send a message from the firebase console and I get nothing.
I refresh and it says the message was sent but I check the console and the device and nothing is there. What am I missing?
Here is my appdelegate:
//
// Created by Erik Grosskurth on 4/24/17.
//
import UIKit
import FirebaseAnalytics
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications
import SystemConfiguration
import MobileCoreServices
import Quickblox
import QuickbloxWebRTC
let kQBApplicationID:UInt = 3545252534
let kQBAuthKey = "udfgsegsetrgsextr"
let kQBAuthSecret = "setbsetbsetbsetrbset"
let kQBAccountKey = "sbrtsbrtbsrtbsrtbrt"
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// [START register_for_notifications]
FirebaseApp.configure()
Messaging.messaging().delegate = self
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()
if (Messaging.messaging().fcmToken != nil) {
DataModel.sharedInstance.sessionInfo.FirebaseAccessToken = Messaging.messaging().fcmToken!
print("FCM token: \(DataModel.sharedInstance.sessionInfo.FirebaseAccessToken)")
}else {
print("token was nil")
}
// [END register_for_notifications]
//Quickblox config
QBSettings.setApplicationID(kQBApplicationID)
QBSettings.setAuthKey(kQBAuthKey)
QBSettings.setAuthSecret(kQBAuthSecret)
QBSettings.setAccountKey(kQBAccountKey)
// Set settings for zone
QBSettings.setApiEndpoint("https://api.quickblox.com", chatEndpoint: "chat.quickblox.com", forServiceZone: .production)
// Activate zone
QBSettings.setServiceZone(.production)
QBSettings.setKeepAliveInterval(30)
QBSettings.setAutoReconnectEnabled(true)
QBRTCConfig.setStatsReportTimeInterval(1)
QBRTCConfig.setDialingTimeInterval(5)
QBRTCConfig.setAnswerTimeInterval(60)
return true
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
Messaging.messaging().appDidReceiveMessage(userInfo)
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("didRegisterForRemoteNotificationsWithDeviceToken()")
Messaging.messaging().apnsToken = deviceToken
//Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.sandbox)
//Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod)
//Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
DataModel.sharedInstance.sessionInfo.APNSAccessToken = deviceTokenString
print("APNS Access Token: \(deviceTokenString)")
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
QBChat.instance().disconnect { (error) in
if error != nil {
print("error: \(String(describing: error))")
} else {
print("success for applicationDidEnterBackground")
}
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
let qbUser = QBUUser()
qbUser.id = DataModel.sharedInstance.qbLoginParams.id
qbUser.password = DataModel.sharedInstance.sessionInfo.QBPassword
QBChat.instance().connect(with: qbUser) { (error) in
if error != nil {
print("error: \(String(describing: error))")
} else {
print("success for applicationWillEnterForeground")
}
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
QBChat.instance().disconnect { (error) in
if error != nil {
print("error: \(String(describing: error))")
} else {
print("success for applicationWillTerminate")
}
}
}
// LOCK IN PORTRAIT MODE
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask(rawValue: UIInterfaceOrientationMask.portrait.rawValue)
}
}
// [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
// With swizzling disabled you must let Messaging know about the message, for Analytics
Messaging.messaging().appDidReceiveMessage(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([])
}
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) {
DataModel.sharedInstance.sessionInfo.FirebaseAccessToken = fcmToken
print("Firebase registration token: \(fcmToken)")
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
Here are the logs:
2017-05-31 16:49:56.937067-0400 Telemed[1843:937699] [Firebase/Analytics][I-ACS003016] Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2017-05-31 16:49:56.937 Telemed[1843] <Warning> [Firebase/Analytics][I-ACS003016] Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2017-05-31 16:49:57.023568-0400 Telemed[1843:937706] [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at
2017-05-31 16:49:57.023 Telemed[1843] <Warning> [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at
2017-05-31 16:49:57.028454-0400 Telemed[1843:937697] [Firebase/Analytics][I-ACS023007] Firebase Analytics v.4000000 started
2017-05-31 16:49:57.028 Telemed[1843] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.4000000 started
2017-05-31 16:49:57.029042-0400 Telemed[1843:937697] [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see )
2017-05-31 16:49:57.029 Telemed[1843] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see )
FCM token: myTokenIsHere
2017-05-31 16:49:57.101756-0400 Telemed[1843:937699] [Firebase/Analytics][I-ACS032003] iAd framework is not linked. Search Ad Attribution Reporter is disabled.
2017-05-31 16:49:57.102 Telemed[1843] <Warning> [Firebase/Analytics][I-ACS032003] iAd framework is not linked. Search Ad Attribution Reporter is disabled.
2017-05-31 16:49:57.103700-0400 Telemed[1843:937697] [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
2017-05-31 16:49:57.103 Telemed[1843] <Notice> [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
Destroyed Session but Saved Login
2017-05-31 16:49:57.158678-0400 Telemed[1843:937637] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-05-31 16:49:57.159102-0400 Telemed[1843:937637] [MC] Reading from public effective user settings.
didRegisterForRemoteNotificationsWithDeviceToken()
APNS Access Token: 091F01B...
>>>------> **SOLVED <-------<<<**
FOR A DEEP DIVE INTO THE TROUBLESHOOTING AND THE ULTIMATE FACEPALM AT THE END... FOLLOW THIS THREAD:
https://github.com/firebase/quickstart-ios/issues/290
SPECIAL THANKS TO THE RIZ FOR HIS TIME IN FIGURING OUT THE ISSUE!!
Firebase Cloud Messaging is quite complex to get set up correctly on iOS, because you have to ensure that your APNs configuration is working, and then add FCM on top of that.
APNs Setup
APNs Authentication Keys are also really nice by apple because they don't expire, works in both sandbox and production environments, and the same key (as a .p8 file) can be used to send push notifications to all apps under that Apple Developer account.
It also introduces a new area for a potential failure: typos. You can type in a random bundle id, and as long as the right "team" is configured in Xcode, your app will happily get an APNs device token.
Sending a notification to that device token via APNs (I used this script to send test notifications over HTTP/2 + Auth Keys) will yield a DeviceTokenNotForTopic error, so that should help you figure out what went wrong.
Checklist
Ensure your app bundle id matches the bundle id you're sending to
Ensure you have an entitlements file, with at least an aps-environment key set to development (this is automatically updated for you in release builds, by Xcode)
If using "automatic" configuration (i.e. swizzling) in other SDKs like Firebase, make sure you're getting an APNs token in application:didRegisterForRemoteNotificationsWithDeviceToken:. That at least confirms that your APNs set up is okay (but still you might have a typo)
FCM Setup
Be sure that the GoogleService-Info.plist file you're using is for the same app as the BUNDLE_ID key in the plist. I've seen developers think that because APNs Keys should work just fine across all of their apps, that the same GoogleService-Info.plist is fine across apps, but that's not the case.
Testing
I'd also recommend sending yourself test notifications using FCM's HTTP API from Terminal, to help debug the issue. Unlike the Firebase Notifications Console, it will give you any raw errors it encounters. Here's an example:
curl -X "POST" "https://fcm.googleapis.com/fcm/send" \
-H "Authorization: key=SERVER_KEY" \
-H "Content-Type: application/json" \
-d $'{
"notification": {
"body": "Testing with direct FCM API",
"title": "Test Message",
"badge": "0",
"sound": "default"
},
"registration_ids": [
"FCM_TOKEN"
]
}'
Fill in your SERVER_KEY with the value in your Firebase Console > Project Settings > Cloud Messaging > Server Key. Replace FCM_TOKEN with your FCM token.
I use Paw to send test notifications to my apps when I'm working on the FCM SDK.
I was using .p8 file for sending notification, though notification wasn't coming; then I realised the Apple Push Notifications service (APNs) wasn't enabled under .p8 file.
After enabling it, all seems to work now.

Firebase Push Notification xcode console received notification but in device it is not working ios Objective c

I am using firebase for PushNotification but there is problem. The notification is received in xcode console not received in device. I am doing everything right but no success to get notification in device
2017-03-31 16:40:44.265 [7188] <Warning> [Firebase/Analytics][I-ACS003016] Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2017-03-31 16:40:44.531 [7188] <Notice> [Firebase/Crash][I-CRA000004] Successfully initialized
2017-03-31 16:40:44.541: <FIRMessaging/INFO> FIRMessaging library version 1.2.2
2017-03-31 16:40:44.552 [7188:141393] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2017-03-31 16:40:44.666 [7188] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3700000 started
2017-03-31 16:40:44.758 [7188] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2017-03-31 16:40:45.124 [7188:141393] Unable to register for remote notifications: Error Domain=NSCocoaErrorDomain Code=3010 "REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION" UserInfo={NSLocalizedDescription=REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION}
2017-03-31 16:40:45.816 [7188:141393] Connected to FCM.
2017-03-31 16:40:45.920 [7188] <Notice> [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
Do you test on a physical, real device or on the simulator? On iOS Simulator you cannot register and receive push notifications :)
If you are working a on a real device, not the simulator, be reminded to call the following functions to register for push.
application.registerUserNotificationSettings(...)
Prior to the call:
https://developer.apple.com/reference/uikit/uiapplication/1623078-registerforremotenotifications
So altogether:
if application.respondsToSelector("registerUserNotificationSettings:") {
if #available(iOS 8.0, *) {
let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
}
}
else {
// Register for Push Notifications before iOS 8
application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
}
Some helpful debugging output could also be:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let pushSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge ,UIUserNotificationType.Sound ,UIUserNotificationType.Alert], categories: nil)
application.registerUserNotificationSettings(pushSettings)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
application.registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let token=deviceToken.description
print(token)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error)
}

Firebase Push Notification iOS issue, Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

I'm trying to implement Firebase Push Notifications for iOS, getting this msg : Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
I'm using Swift 2.3, Xcode 8.
I have already set the APNs SSL Certificates in the Firebase Console, also have enable the Push Notification in Xcode App > Capabilities and check marked the Remote Notification option in BackgroundMode.
Also added FirebaseAppDelegateProxyEnabled = No in Info.plist and the correct Bundle ID in GoogleService-Info.plist
One weird thing is happening that if I don't Enable the the Push Notification in Xcode App > Capabilities, I don't get the error, it prints the User Info and the Token :(
Kindly help.
Below is my AppDelegate code and the Output
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//for Firebase
// [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()
// [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 comes here")
//print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
print("message comes here end")
}
// [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]
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
// [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]
--------OUTPUT
2016-10-20 15:50:03.051 ProgrammingHub[2747:916824] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2016-10-20 15:50:04.073 ProgrammingHub[2747:916824] [Crashlytics] Version 3.7.2 (112)
2016-10-20 15:50:04.287 ProgrammingHub[2747] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-10-20 15:50:04.314: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-10-20 15:50:04.326: <FIRMessaging/INFO> FIRMessaging library version 1.2.0
2016-10-20 15:50:04.380 ProgrammingHub[2747:] <FIRAnalytics/INFO> Firebase Analytics v.3404000 started
2016-10-20 15:50:04.382 ProgrammingHub[2747:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http:/goo.gl/Y0Yjwu)
2016-10-20 15:50:04.692 ProgrammingHub[2747:916824] INFO: GoogleAnalytics 3.11 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002
2016-10-20 15:50:04.988 ProgrammingHub[2747:916824] INFO: GoogleAnalytics 3.11 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002
2016-10-20 15:50:05.208 ProgrammingHub[2747:] <FIRAnalytics/INFO> Firebase Analytics enabled
2016-10-20 15:50:05.391 ProgrammingHub[2747:916926] INFO: GoogleAnalytics 3.11 -[GAIBatchingDispatcher hitsForDispatch] (GAIBatchingDispatcher.m:368): No pending hits.
2016-10-20 15:50:06.166 ProgrammingHub[2747] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
Try updating Firebase/Core to v3.4.4, it fixed unexpected errors for me. Also, avoid calling unregisterForRemoteNotifications. After this call, you can't register the device anymore to push notifications.

Firebase when receive Push Notification did not receive the popup

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
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];
}
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.
I have same configuration you have and it works like AdamK said. (While in background mode, notification appears.) Also check your certificates.
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.
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)
}
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.

Resources