ios - 没有收到来自 Firebase 控制台的推送通知
问题描述
我已经实施了有关实施推送通知的所有步骤,但是当我测试通知时,控制台它不会出现在 iPhone 上,但是当我使用来自“ https://pushtry.com/的密码 n 令牌”的生产 apns 证书 n 进行测试时“它工作正常。我无法纠正为什么会这样。我还启用了功能部分的推送通知。谢谢在我的应用程序委托代码下面
mport Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate,MessagingDelegate,UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("AIzaSyB5HWsalLBmBFjLC3NjTUF2KB7i5zvz45k")
GMSPlacesClient.provideAPIKey("AIzaSyB5HWsalLBmBFjLC3NjTUF2KB7i5zvz45k")
let notificationCenter = UNUserNotificationCenter.current()
// It is For Notification Allow Authentications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
guard isGranted else { return }
self.getNotificationSettings()
if err != nil {
//Something bad happend
print("Erroo ocured......")
} else {
print(" Success.........All good")
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self // it is very important to Generate Firebase registration token, otherwise "didReceiveRegistrationToken" method will not called.
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
FirebaseApp.configure()
return true
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async(execute: { UIApplication.shared.registerForRemoteNotifications() })
}
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
{
print("Firebase registration token::::::: \(fcmToken)")
UserDefaults.standard.set(fcmToken, forKey: "deviceToken")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//NSLog("[RemoteNotification] applicationState: \(applicationStateString) didReceiveRemoteNotification for iOS9: \(userInfo)")
if UIApplication.shared.applicationState == .active {
//TODO: Handle foreground notification
} else {
//TODO: Handle background notification
}
// Print full message.
print(userInfo)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// show the notification alert (banner), and with sound
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// tell the app that we have finished processing the user’s action / response
let application = UIApplication.shared
if(application.applicationState == .active){
print("user tapped the notification bar when the app is in foreground")
}
if(application.applicationState == .inactive)
{
print("user tapped the notification bar when the app is in background")
}
completionHandler()
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
}
解决方案
**首先您应该检查所有证书类型的东西是否正确** 之后在 appdelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// START register for notifications
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()
// END register for notifications
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Result \(result)")
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.hexString
}
还将您的 p.12 文件上传到 firebase 控制台
推荐阅读
- c++ - 只有 2 和 5 作为数字的特殊数字
- html - 似乎无法让我的 css 网格在整个页面宽度上拉伸
- c++ - 如何知道 Visual Studio 的构建命令是什么?
- javascript - 如何维护每个输入文本的消息位置?
- spring - Springboot 2.3.x 应用程序在启动时卡住
- python - 使用 Beautiful Soup 从 HTML 标签中提取数据
- python - 未找到 MySQL.connector 模块
- postgresql - Postgres:附加到大型 jsonb 数组是否昂贵?
- sql - 如何编写一个 sql where 过滤器,它将返回时间戳大于给定日期和时间的行?
- batch-file - 如何编写一个 Windows 批处理文件,通过数值更新文件夹中的所有文件名?