我遵循以下所有步骤并在 App Delegate
中添加了适当的导入和代码。我还确保在运行该应用程序时允许接受通知。
按照以下步骤,为什么我从 Firebase Cloud Messaging Console 发送通知后收不到通知?
在我的开发者帐户中,我转到了
Certificates, Identifiers & Profiles
在
Keys
下,我选择了All
并单击了右上角的添加按钮 (+)在
Key Description
下,我为签名 key 输入了一个唯一的名称在
Key Services
下,我选中了APNs
复选框,然后单击Continue
,然后单击Confirm
我复制了
key ID
(在第 7 步中使用)并单击了下载
以生成并下载.p8
key我转到
Firebase
,单击齿轮图标
>项目设置
>云消息传递
< strong>(不是像第 10 步那样的 Grow > Cloud Messaging)在
iOS 应用程序配置
>APNs 身份验证 key
下,我转到了第一部分APNs 身份验证 key
(不是 APNs 证书),选择Upload
并上传.p8
key 、Key ID
和我的Team Id
。teamId
位于Membership
部分,keyId 是xxxxxxx
.p8 文件的xxxxxxx
部分。在我的 Xcode 项目中,我转到
Capabilities
>Background Modes
,将其打开On
,然后选中Remote Notifications
然后我转到 >
Push Notifications
并将其打开On
,它会自动为应用程序生成一个Entitlement Certificate
(它在里面项目导航器)要在 Firebase 中发送通知,我去了
Grow
>Cloud Messaging
>Send Your First Message
>1 .通知文本
输入了一些随机字符串>2。 Target
并选择了我的应用程序的bundleId
>3。立即安排
> 4. 按下一步 > 5. 选择声音
和角标(Badge)
>回顾
在AppDelegate中我添加了
import UserNotifications
,import FirebaseMessaging
,import Firebase
,注册了UNUserNotificationCenterDelegate
并添加了下面的代码。设置 reCAPTCHA verification我转到
Blue Project Icon
>Info
>URL Types
然后在URL Schemes
部分(按加号如果什么都没有,请签署+
),我从我的GoogleService-Info.plist
输入了
REVERSED_CLIENT_ID
我在下面的所有打印语句中添加了断点,在我从 Firebase 发送消息后,没有一个被命中。
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)
}
}
如下图所示,消息已成功发送,但我从未收到。
最佳答案
我认为您还应该将此添加到您的代码中,否则您将不会收到推送通知。 Firebase 现在需要知道 apns token 是什么来向您发送推送。
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
关于使用 .p8 文件后未收到 iOS Firebase 云消息通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52683855/