无法在苹果商店的 ios 设备上接收通知(fcm)

Posted

技术标签:

【中文标题】无法在苹果商店的 ios 设备上接收通知(fcm)【英文标题】:Can not receive notification(fcm) on ios device from apple store 【发布时间】:2018-08-20 03:51:45 【问题描述】:

为什么我在 ios 设备上构建应用程序时显示消息,但将应用程序推送到苹果商店时没有收到通知。

我启用了推送通知功能 enter image description here

这是 Appdelegate 文件的所有代码

访问https://ideone.com/ErsdDS查看代码

代码

import UIKit
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications
import GoogleMaps
import GooglePlaces
import CoreData
 
//import MessagingDelegate
@available(iOS 10.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,MessagingDelegate 
    static var mangedObjectContext: NSManagedObjectContext?
    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"
    let key = "AIzaSyDzuGKTfmkbR_VBffp....11Gz7pFOX2c"
 
 
//
//    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
//
//
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
        ///
        FirebaseApp.configure()
        GMSServices.provideAPIKey("AIzaSyD2kiw....qFi-z2-iEzdcbvloSNOweBo")
        GMSPlacesClient.provideAPIKey("AIzaSyD2ki....1qFi-z2-iEzdcbvloSNOweBo")
        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        // Register for remote notifications. This shows a permission dialog on first run, to
        // show the dialog at a more appropriate time move this registration accordingly.
        // [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()
 
 
        //
 
        AppDelegate.mangedObjectContext = persistentContainer.viewContext
        return true     
    
 
 
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) 
 
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    
 
    print(userInfo)

 
    func applicationDidFinishLaunching(_ application: UIApplication) 
        FirebaseApp.configure()
        GMSServices.provideAPIKey("AIzaSyD2kiwgq9e1qFi-z2-iEzdcbvloSNOweBo")
        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        // Register for remote notifications. This shows a permission dialog on first run, to
        // show the dialog at a more appropriate time move this registration accordingly.
        // [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()
 
 
 
    
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) 
 
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    
 
    print(userInfo)
 
    completionHandler(UIBackgroundFetchResult.newData)

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) 
    print("Unable to register for remote notifications: \(error.localizedDescription)")

 
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 
    print("APNs token retrieved: \(deviceToken)")
 

    func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) 
        Messaging.messaging().apnsToken = deviceToken as Data
    
 
    func applicationWillResignActive(_ application: UIApplication) 
    
 
    func applicationDidEnterBackground(_ application: UIApplication) 
    
 
    func applicationWillEnterForeground(_ application: UIApplication) 
    
 
    func applicationDidBecomeActive(_ application: UIApplication) 
    
 
    func applicationWillTerminate(_ application: UIApplication) 
    
    lazy var persistentContainer: NSPersistentContainer = 
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "Model")
        container.loadPersistentStores(completionHandler:  (storeDescription, error) in
            if let error = error as NSError? 
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            
        )
        return container
    ()
 
    // MARK: - Core Data Saving support
 
    func saveContext () 
        let context = persistentContainer.viewContext
        if context.hasChanges 
            do 
                try context.save()
             catch 
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            
        
    
 

 
@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([.alert,.sound])
    
 
    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()
    

@available(iOS 10.0, *)
extension AppDelegate  
    // [START refresh_token]
 
 
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) 
        print("Firebase registration token: \(fcmToken)")
        InstanceID.instanceID().instanceID  (result, error) in
            if let error = error 
                print("Error fetching remote instange ID: \(error)")
             else if let result = result 
                print("Remote instance ID token: \(result.token)")
                tokenfb = result.token
                print("tao dang tesst: \(tokenfb)")
 
        
            saveCache(key: "tokenfb", value: tokenfb)
        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    

    // [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]

*请帮帮我!

【问题讨论】:

你能检查一下这个问题***.com/questions/47234355/… @KiranSarvaiya 是的。我正在测试该解决方案。谢谢你的帮助 【参考方案1】:
 func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) 

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)

FIRInstanceIDAPNSTokenType.Sandbox 在我们从 TestFlight 下载或在开发模式下进行测试时使用,FIRInstanceIDAPNSTokenType.Prod 在我们发布生产版本或从 AppStore 下载时使用

【讨论】:

当我将上面的代码粘贴到错误消息中时,我已经修复了它 //InstanceID.instanceID().setAPNSToken(deviceToken, type: .prod) 但它通知 instancelD () 该属性是setAPNSToken 我刚刚找到了一种从 firebase 4.0 开始保存令牌的新方法 //Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod) 我在调试模式下尝试过,正在等待苹果商店的批准以测试其性能我会向您报告测试结果:)) @TrầnBìnhMinh 当然:) 请帮帮我!

以上是关于无法在苹果商店的 ios 设备上接收通知(fcm)的主要内容,如果未能解决你的问题,请参考以下文章

无法接收 iOS 的 FCM 推送通知

FCM 生产 APN 不起作用

iOS 无法通过 FCM 接收推送通知(可以通过 APNs)

无法接收 FCM 推送通知 IOS - 目标 C

通过向 FCM 单个设备发送通知来反应本机 Firebase iOS 生产无法正常工作

在 iOS 9.2 上无法接收 FCM 主题消息