当前位置: 首页 > 面试题库 >

FCM推送通知在iOS 11中不起作用

郭彬郁
2023-03-14
问题内容

我需要处理推送通知,这是通过较低版本的ios完成的,但是在ios 11中,从未收到任何推送通知。我使用Firebase Cloud
Messaging。请任何人有解决方案,然后请分享。


问题答案:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Use Firebase library to configure APIs
FirebaseApp.configure()
self.registerForPushNotifications(application: application)
Messaging.messaging().delegate = self

    if let token = InstanceID.instanceID().token() {
        NSLog("FCM TOKEN : \(token)")
        DataModel.sharedInstance.onSetUserFCMStringToken(FCM: token)
        self.connectToFcm()
    }
    if launchOptions != nil {
        //opened from a push notification when the app is closed
        _ = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] ?? [AnyHashable: Any]()
    }
    else {
        //opened app without a push notification.
    }
    return true
}

@available(iOS 10,*)

extension AppDelegate: UNUserNotificationCenterDelegate {
// iOS10+, called when presenting notification in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    NSLog("[UserNotificationCenter] willPresentNotification: \(userInfo)")
    //TODO: Handle foreground notification
    completionHandler([.alert])
}

// iOS10+, called when received response (default open, dismiss or custom action) for a notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    NSLog("[UserNotificationCenter] didReceiveResponse: \(userInfo)")
    //TODO: Handle background notification
    completionHandler()
}}

extension AppDelegate : MessagingDelegate {
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
}

// Receive data message on iOS 10 devices while app is in the foreground.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    NSLog("remoteMessage: \(remoteMessage.appData)")
}}

//Register for push notification.
func registerForPushNotifications(application: UIApplication) {
    if #available(iOS 10.0, *) {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert,.sound]) { (granted, error) in
            if error == nil{
                DispatchQueue.main.async(execute: {
                    application.registerForRemoteNotifications()
                })
            }
        }
    }
    else {

        let settings = UIUserNotificationSettings(types: [.alert,.sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    // Add observer for InstanceID token refresh callback.
    NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

}

@objc func tokenRefreshNotification(_ notification: Notification) {
    print(#function)
    if let refreshedToken = InstanceID.instanceID().token() {
        NSLog("Notification: refresh token from FCM -> \(refreshedToken)")

    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm() {
    // Won't connect since there is no token
    guard InstanceID.instanceID().token() != nil else {
        NSLog("FCM: Token does not exist.")
        return
    }

    Messaging.messaging().shouldEstablishDirectChannel = true
}

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


// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {


    Messaging.messaging().apnsToken = deviceToken


}

// iOS9, called when presenting notification in foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    NSLog("didReceiveRemoteNotification for iOS9: \(userInfo)")

}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {




}


 类似资料:
  • 我们用FCM创建了一个带有通知的聊天应用程序,我的代码是正确的,我的设备也得到了推送通知数据,但一些中国制造的设备,如vivo、oppo、一加、小米,不允许通知显示,除非我在各自厂商的受保护的应用程序列表中添加应用程序。他们有没有办法解决这个问题。 https://hackernoon.com/notifications-in-android-are-horribly-broken-b8dbec6

  • 此代码未生成推送。 //自定义通知视图RemoteViews contentView=新建RemoteViews(getPackageName(),r.layout.custom_push);ContentView.SetImageViewResource(r.id.image,r.mipmap.ic_launcher);contentview.settextviewtext(r.id.title

  • 我是新来的< code>Android Studio,所以我不明白。我是使用< code>FCM的< code >推送通知的新手,但我没有得到解决方案。我在运行时遇到了这种错误。 我的应用程序/Gradle 这是我的项目等级 我已经更新了android studio<code>SDK</code>我这边什么都没有了,但我不知道我哪里出错了。所以请在这方面帮助我。

  • 问题内容: 我在iOS上的FCM通知有问题。 我收到成功通知时,我的应用程序是在前台(回调中被激发),但是当应用程序在后台(我看不出在iOS中的通知栏的任何东西)我没有收到通知。 因此,我认为问题在于FCM发送的消息格式。我的服务器发送到FCM的json格式如下: 如您所见,我的json中有两个块:一个通知块(用于在后台接收通知)和一个数据块(用于在前台接收通知)。 我不明白为什么没有收到后台通知

  • 以下是我的通知案例:当通知到达时,应用程序可能是前台,后台,或关闭 2.后台:当用户点击通知时,应用程序应显示在前面,并显示主要活动 3.App关闭时:当用户点击通知时,App应打开,并显示主要活动。 当我用设置intent和用设置PendingIntent时。它按预期工作,但当用户点击notification时,它不会调用Main Activity的onCreate方法。 如果您考虑了上面的代码

  • 最近,我在我的应用程序中更改了“googleservices.json”文件。之前的开发人员使用不同的“googleservices.json”文件,所以我更改了它以获取firebase分析。我没有访问之前Firebase项目的权限,因此无法使用Firebase analytics。在更改了“googleservices.json”文件后,我的应用程序中没有收到推送通知。我需要从后端更改什么吗?提