Reputation: 19612
I followed all the steps below and added the appropriate imports and code in App Delegate
. I also made sure I allowed Notifications to be accepted when I ran the app.
Following the steps below, why is it that I can't receive the Notifications after I send one from the Firebase Cloud Messaging Console ?
In my Developer account I went to Certificates, Identifiers & Profiles
Under Keys
, I selected All
and clicked the Add button (+) in the upper-right corner
Under Key Description
, I entered a unique name for the signing key
Under Key Services
, I selected the APNs
checkbox, then clicked Continue
then clicked Confirm
I copied the Key ID
(used in step 7) and clicked Download
to generate and download the .p8
key
I went to Firebase
, clicked the Gear Icon
> Project Settings
> Cloud Messaging
(not Grow > Cloud Messaging like step 10)
Under iOS app configuration
> APNs Authentication Key
I went to the first section APNs Authentication Key
(NOT APNs Certificates), selected Upload
and uploaded the .p8
key, the Key ID
, and my Team Id
. The teamId
is located in the Membership
section and the keyId is the xxxxxxx
part of the xxxxxxx
.p8 file.
In my Xcode project I went to Capabilities
> Background Modes
, turned it On
, and checked Remote Notifications
Then I went to > Push Notifications
and turned it On
which automatically generated an Entitlement Certificate
for the app (it's inside the project navigator)
To send a notification in Firebase I went to Grow
> Cloud Messaging
> Send Your First Message
> 1. Notification Text
entered some random String > 2. Target
and selected my app's bundleId
> 3. Scheduling Now
> 4. pressed Next > 5. selected sound
and a badge
> Review
In AppDelegate I added import UserNotifications
, import FirebaseMessaging
, import Firebase
, registered for the UNUserNotificationCenterDelegate
and added the code below.
To set up the reCAPTCHA verification I went to the Blue Project Icon
> Info
> URL Types
then in the URL Schemes
section (press the plus sign +
if nothing is there), I entered in the REVERSED_CLIENT_ID
from my GoogleService-Info.plist
I've added break points to all the print statements below and after I send a message from Firebase none of them get hit.
import UserNotifications
import FirebaseMessaging
import Firebase
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.sound,.alert,.badge]) {
[weak self] (granted, error) in
if let error = error {
print(error.localizedDescription)
return
}
print("Success")
}
application.registerForRemoteNotifications()
} else {
let notificationTypes: UIUserNotificationType = [.alert, .sound, .badge]
let notificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)
}
}
// MARK:- UNUserNotificationCenter Delegates
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
var token = ""
for i in 0..<deviceToken.count{
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration Succeded! Token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Notifcation Registration Failed: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let gcm_message_id = userInfo["gcm_message_id"]{
print("MessageID: \(gcm_message_id)")
}
print(userInfo)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
print("Handle push from foreground \(notification.request.content.userInfo)")
let dict = notification.request.content.userInfo["aps"] as! NSDictionary
let d = dict["alert"] as! [String:Any]
let title = d["title"] as! String
let body = d["body"] as! String
print("Title:\(title) + Body:\(body)")
showFirebaseNotificationAlertFromAppDelegate(title: title, message: body, window: self.window!)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("\(response.notification.request.content.userInfo)")
if response.actionIdentifier == "yes"{
print("True")
}else{
print("False")
}
}
func showFirebaseNotificationAlertFromAppDelegate(title: String, message: String, window: UIWindow){
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
window.rootViewController?.present(alert, animated: true, completion: nil)
}
}
The message gets sent successfully as you can see in the below pic but I never receive it.
Upvotes: 1
Views: 2226
Reputation: 167
I think you should also add this to your code otherwise you won't be receiving the push notifications. Firebase needs to now what the apns token is to send you the pushes.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
Upvotes: 4
Reputation: 19612
I got the answer from here
I was supposed to add Messaging.messaging().delegate = self
BEFORE FirebaseApp.configure()
I also had to add in the Messaging Delegate to receive the FCM Registration Token.
Inside didFinishLaunching
add Messaging.messaging().delegate = self
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Messaging.messaging().delegate = self // make sure this is added BEFORE FirebaseApp.Configure
FirebaseApp.configure()
// all the other code inside didFinishLaunching goes here...
}
// all the other methods from above goes here...
****Also at the bottom of the AppDelegate file add the Messaging Delegate and it's method. This is where the FCM Token
is received:
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Your Firebase FCM Registration Token: \(fcmToken)")
}
}
Upvotes: 0
Reputation: 167
seems like you are missing some of the configuration for the FCM to work properly.
From what I see you aren't sending the token to firebase and you aren't registering for the FCM.
See the documentation here https://firebase.google.com/docs/cloud-messaging/ios/client for more details.
To send the push message through the firebase you need to have the FCM token. The token you are using is the one coming from the APNS servers and you need to forward it to firebase.
Upvotes: 0