菜鸟教程小白 发表于 2022-12-11 19:19:35

ios - Firebase 通知未在 iOS 应用程序中显示警报或横幅和角标(Badge)应用程序图标


                                            <p><ul>
<li>我设计了一个启用推送通知的 iOS 应用。
通过 FCM 抛出的通知(仅用于检查),它只会在前台模式下在控制台中打印。但是当应用处于后台模式时,它不会显示任何通知。</li>
<li>我已在 Apple Developer Program 帐户中注册。 </li>
<li>在此帐户中,我创建了一个启用推送通知和证书(用于生产)的应用 ID。</li>
<li>创建了 .p12 和 .pem 文件。 </li>
<li>还创建了 Provisioning Profile (AdHoc)</li>
<li>在 Firebase 中为 iOS 10+ 的 xcode 8 中的通知实现代码。</li>
<li>正确生成的设备 token 。
仍然无法收到通知。请帮忙..</li>
</ul>

<p>Appdelegate 代码:</p>

<pre><code>import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    let gcmMessageIDKey = &#34;gcm.message_id&#34;

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: ?) -&gt; Bool {

      // 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.
      //
      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 })

            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

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

      application.registerForRemoteNotifications()

      //
      FIRApp.configure()

      //
      // Add observer for InstanceID token refresh callback.
      NotificationCenter.default.addObserver(self,
                                             selector: #selector(self.tokenRefreshNotification),
                                             name: .firInstanceIDTokenRefresh,
                                             object: nil)
      //
      return true
    }

    /* */
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: ) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification
      // Print message ID.
      if let messageID = userInfo {
            print(&#34;Message ID: \(messageID)&#34;)
      }

      // Print full message.
      print(userInfo)
    }

    /*
    */
    func tokenRefreshNotification(_ notification: Notification) {
      if let refreshedToken = FIRInstanceID.instanceID().token() {
            print(&#34;InstanceID token: \(refreshedToken)&#34;)
      }

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

    /*
   / */
    func connectToFcm() {
      // Won&#39;t connect since there is no token
      guard FIRInstanceID.instanceID().token() != nil else {
            return;
      }

      // Disconnect previous FCM connection if it exists.
      FIRMessaging.messaging().disconnect()

      FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print(&#34;Unable to connect with FCM. \(error)&#34;)
            } else {
                print(&#34;Connected to FCM.&#34;)
            }
      }
    }

    /* 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) {
      print(&#34;APNs token retrieved: \(deviceToken)&#34;)

      // With swizzling disabled you must set the APNs token here.
      // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)

      if let refreshedToken = FIRInstanceID.instanceID().token() {
            print(&#34;InstanceID token 1: \(refreshedToken)&#34;)
      }
    }


    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: ,
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification
      // Print message ID.
      if let messageID = userInfo {
            print(&#34;Message ID in didReceiveRemoteNotification: \(messageID)&#34;)
      }

      // Print full message.
      print(&#34;didReceiveRemoteNotification: \(userInfo)&#34;)

      completionHandler(UIBackgroundFetchResult.newData)
    }

    //
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      print(&#34;Unable to register for remote notifications: \(error.localizedDescription)&#34;)
    }



    /* */
    func applicationDidBecomeActive(_ application: UIApplication) {
      connectToFcm()
    }


   /*
   */
    func applicationDidEnterBackground(_ application: UIApplication) {
      //FIRMessaging.messaging().disconnect()
       // print(&#34;Disconnected from FCM.&#34;)

      connectToFcm()
          print(&#34;connected to FCM in Background.&#34;)
    }
    //
}

extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {
      let userInfo = notification.request.content.userInfo
      // Print message ID.
      if let messageID = userInfo {
            print(&#34;Message ID in UNUserNotificationCenterDelegate: \(messageID)&#34;)
      }

      // Print full message.
      print(userInfo)

      // Change this to your preferred presentation option
      completionHandler([])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -&gt; Void) {
      let userInfo = response.notification.request.content.userInfo
      // Print message ID.
      if let messageID = userInfo {
            print(&#34;Message ID in userNotificationCenter: \(messageID)&#34;)
      }

      // Print full message.
      print(userInfo)

      completionHandler()
    }
}

extension AppDelegate : FIRMessagingDelegate {

    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
      print(&#34;applicationReceivedRemoteMessage: \(remoteMessage.appData)&#34;)
    }

}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>要在后台模式下接收和显示通知,只需确保您已在“功能”部分启用“推送通知”。 </p>

<p>要在前台模式下显示通知,请在 willPresent 方法中将警报、角标(Badge)和声音参数添加到您的完成 block 。</p>

<p><em>completionHandler([.alert, .badge, .sound])</em></p>

<pre><code> // Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo {
      print(&#34;Message ID in UNUserNotificationCenterDelegate: \(messageID)&#34;)
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .badge, .sound])
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Firebase 通知未在 iOS 应用程序中显示警报或横幅和角标(Badge)应用程序图标,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42924888/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42924888/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Firebase 通知未在 iOS 应用程序中显示警报或横幅和角标(Badge)应用程序图标