admin管理员组

文章数量:1289586

App.js:296 Error in token retrieval: NativeFirebaseError: [messaging/unknown] The operation couldn’t be completed. No APNS token specified before fetching FCM Token

Getting Error while fetching FCM Token in IOS.

**This is my AppDelegate.swift file may be the problem is from here **

import UIKit
import Firebase
import UserNotifications
import RNCPushNotificationIOS
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider

@main
class AppDelegate: RCTAppDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    
    // Initialize Firebase
    FirebaseApp.configure();

    Messaging.messaging().delegate = self

    // Set the UNUserNotificationCenter delegate to self
    UNUserNotificationCenter.current().delegate = self
  
    // Register for remote notifications
    application.registerForRemoteNotifications()

    // Request notification permissions
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
      if let error = error {
        print("Error requesting notification permissions: \(error)")
      }
      print("Notification permission granted: \(granted)")
    }

    // You can add your custom initial props in the dictionary below.
    // They will be passed down to the ViewController used by React Native.
    self.initialProps = [:]
    self.moduleName = "*****"
    self.dependencyProvider = RCTAppDependencyProvider()

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  // // Handle foreground notifications: show alert, sound, and badge even when app is active.
  // func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  //   completionHandler([.badge, .sound])
  // }

  // // Optionally, handle notification responses if needed.
  // func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  //   // Process the notification response (for example, navigate to a specific screen)
  //   completionHandler()
  // }

  override func sourceURL(for bridge: RCTBridge) -> URL? {
    self.bundleURL()
  }

  override func bundleURL() -> URL? {
  #if DEBUG
    RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
  #else
    Bundle.main.url(forResource: "main", withExtension: "jsbundle")
  #endif
  }

  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
  }
}

This is checkAndGetFcmToken function from App.js where i need token.

  async function checkAndGetFcmToken() {
    try {
      if (Platform.OS === 'ios') {
        await messaging().registerDeviceForRemoteMessages();
      }

      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
        );
        if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Notification permission not granted');
          return;
        }
      }

      const authStatus = await messaging().requestPermission();
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;


      if (enabled) {
       
          const token = await messaging().getToken();
          console.log('FCM token:', token);
          if (token) {
            await AsyncStorage.setItem('fcmToken', token);
          } else {
            console.warn('FCM token is still null.');
          }
      
      } else {
        console.log('Notification permission not granted');
      }

    } catch (error) {
      console.error('Error in token retrieval:', error);
    }
  }

enter image description here

本文标签: Push Notification IOS Setup in React Native Latest Version 0770Stack Overflow