问题
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 selectedAll
and clicked the Add button (+) in the upper-right cornerUnder
Key Description
, I entered a unique name for the signing keyUnder
Key Services
, I selected theAPNs
checkbox, then clickedContinue
then clickedConfirm
I copied the
Key ID
(used in step 7) and clickedDownload
to generate and download the.p8
keyI went to
Firebase
, clicked theGear Icon
>Project Settings
>Cloud Messaging
(not Grow > Cloud Messaging like step 10)Under
iOS app configuration
>APNs Authentication Key
I went to the first sectionAPNs Authentication Key
(NOT APNs Certificates), selectedUpload
and uploaded the.p8
key, theKey ID
, and myTeam Id
. TheteamId
is located in theMembership
section and the keyId is thexxxxxxx
part of thexxxxxxx
.p8 file.In my Xcode project I went to
Capabilities
>Background Modes
, turned itOn
, and checkedRemote Notifications
Then I went to >
Push Notifications
and turned itOn
which automatically generated anEntitlement 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'sbundleId
>3. Scheduling Now
> 4. pressed Next > 5. selectedsound
and abadge
>Review
In AppDelegate I added
import UserNotifications
,import FirebaseMessaging
,import Firebase
, registered for theUNUserNotificationCenterDelegate
and added the code below.To set up the reCAPTCHA verification I went to the
Blue Project Icon
>Info
>URL Types
then in theURL Schemes
section (press the plus sign+
if nothing is there), I entered in theREVERSED_CLIENT_ID
from myGoogleService-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.
回答1:
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
}
回答2:
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.
回答3:
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)")
}
}
来源:https://stackoverflow.com/questions/52683855/ios-firebase-cloud-messaging-notifications-not-being-received-after-using-p8-fi