Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show local notification when the app is opened in iOS

I'm using flutter_local_notifications package and it's showing notifications when the app is opened (foreground) in Android but not in the iOS. The docs says:

For iOS 10+, use the presentation options to control the behaviour for when a notification is triggered while the app is in the foreground. The default settings of the plugin will configure these such that a notification will be displayed when the app is in the foreground.

If I understood it right, I don't need to do anything on my own except (correct me if I'm wrong and this is what the question is all about). This is the code I'm using. (Works in both iOS and Android except the foreground part)

Future<void> showNotification() async {
  final notificationPlugin = FlutterLocalNotificationsPlugin();
  const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
  const iOSSettings = IOSInitializationSettings();
  final initializationSettings = InitializationSettings(
    android: androidSettings,
    iOS: iOSSettings,
  );
  await notificationPlugin.initialize(
    initializationSettings,
    onSelectNotification: (payload) async {},
  );

  const androidNotificationDetails = AndroidNotificationDetails(
    'foo_id',
    'Foo Name',
    'Foo description ',
    importance: Importance.max, 
    priority: Priority.defaultPriority,
    showWhen: false,
  );

  await notificationPlugin.show(
    1211, 
    'Notification title',
    'Notification body',
    NotificationDetails(android: androidNotificationDetails),
    payload: 'item x',
  );
}
like image 717
iDecode Avatar asked Sep 05 '25 07:09

iDecode


2 Answers

in AppDelegate.swift try add the following :

  • Swift:
    if #available(iOS 10.0, *) {
              UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
            }
            func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
                     completionHandler([.alert, .badge, .sound])
                }
  • Objective-C:
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0.0")) {
 (void)userNotificationCenter:(UNUserNotificationCenter *)center 
       willPresentNotification:(UNNotification *)notification 
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler;
}

like image 156
Noha El Sheweikh Avatar answered Sep 07 '25 21:09

Noha El Sheweikh


Add this code to your project :

await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
like image 31
Lala Naibova Avatar answered Sep 07 '25 20:09

Lala Naibova