firebase 点击通知后,应用程序终止时,Flutter iOS应用程序未打开

olmpazwi  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(196)

我在应用中实现了FCM推送通知,一切正常。但在iOS上,点击通知后应用不会打开,而应用会终止。我使用云函数通过FCM admin SDK发送HTTP通知。对于客户端通知,我使用Awesome Notification
注意一:应用程序在通知点击时打开,而应用程序在前台/后台。
注二:我收到一个通知,而应用程序被终止。但没有打开应用程序后,点击通知。

主省道

importing all imports

  Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  await AwesomeNotifications().createNotificationFromJsonData(message.data);
}

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();

// Firebase Messaging Initialization
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

NotificationSettings settings = await firebaseMessaging.requestPermission(
   alert: true,
   badge: true,
   provisional: false,
   sound: true,
);

 await AwesomeNotifications().initialize(
  // set the icon to null if you want to use the default app icon
  null,
  [
    NotificationChannel(
      channelGroupKey: 'notiGroup_key',
      channelKey: 'noti_key',
      channelName: 'notiChannel_name',
      channelDescription: 'notiChannel_desc',
      defaultColor: const Color(0xFF9D50DD),
      ledColor: Colors.white,
    ),
  ]);
 AwesomeNotifications()
  .actionStream
  .listen((ReceivedNotification receivedNotification) {});

  final RemoteMessage? message = await firebaseMessaging.getInitialMessage();

  await firebaseMessaging.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
   );

   FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
       if (notification != null && android != null) {
      await AwesomeNotifications().createNotification(
      content: message.data['image'].toString() == ''
        ? NotificationContent(
            id: 10,
            channelKey: 'noti_key',
            title: notification.title,
            body: notification.body,
          )
        : NotificationContent(
            id: 10,
            channelKey: 'noti_key',
            title: notification.title,
            body: notification.body,
            bigPicture: message.data['image'],
            notificationLayout: NotificationLayout.BigPicture,
                  ),
             );
           }
        });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
   if (message.notification != null &&
   message.data['type'].toString() == 'order') {
   var order =
      await orderCollection.doc('zTuAXK4goqIErVHPqPIZQqkAKJKs').get();
  OrderModel newOrder = OrderModel.fromJson(order.data()!);

  Get.to(
    () => OrderDetailsScreen(
      order: newOrder,
      ),
    );
  }
 });

if (getStorage.read('isLogin') != true) {
await FirebaseMessaging.instance.subscribeToTopic('AllUsers');
   } else if (getStorage.read('isLogin') == true) {
FirebaseMessaging.instance.getToken().then((token) async {
  print('token : $token');
  await userCollection
      .doc(auth.currentUser!.uid)
      .update({'deviceToken': token});
});
FirebaseMessaging.instance.onTokenRefresh.listen((token) async {
  await userCollection
      .doc(auth.currentUser!.uid)
      .update({'deviceToken': token});
  });
}
runApp(MyApp(
  message: message,
  ));
}

class MyApp extends StatefulWidget {
final RemoteMessage? message;

const MyApp({super.key, required this.message});

@override
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
  if (widget.message != null) {
    Future.delayed(const Duration(milliseconds: 1000), () async {
      await Navigator.push(
          context, MaterialPageRoute(builder: (_) => const HomeScreen()));
      });
    }
  });
  super.initState();
}

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
  title: 'Demo App',
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.blue,
    fontFamily:'Poppins',
    progressIndicatorTheme: const ProgressIndicatorThemeData(
      color: goldenColor,
    ),
  ),
  
  initialBinding: ControllersBinding(),
  home: const SplashScreen(),
  builder: EasyLoading.init(),
      );
     }
   }

应用代理.swift

import UIKit
import Flutter
import GoogleMaps
import Firebase
import FirebaseAuth
import FirebaseMessaging

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
GMSServices.provideAPIKey("ANY API KEY")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

override func application(_ application: UIApplication,
  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Auth.auth().setAPNSToken(deviceToken, type: .prod)

    Messaging.messaging().apnsToken = deviceToken
   super.application(application,
   didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
     }
  }
cqoc49vn

cqoc49vn1#

打开ios/Runner/AppDelegate.swift
你需要把这个代码

FirebaseApp.configure()

在这之前

GeneratedPluginRegistrant.register(with: self)

你会看到AddDelegate.swift是这样的。

import UIKit
import Flutter
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

相关问题