firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.72k stars 3.97k forks source link

🐛 [firebase_messaging] iOS Foreground Notifications Not working On Any Real Device #5085

Closed Zulqurnain closed 3 years ago

Zulqurnain commented 3 years ago

Bug report

Describe the bug Notifications of firebase are not working on iOS in foreground no matter what I do so far I have tried following things to solve the issue:

Steps to reproduce

Steps to reproduce the behavior:

  1. Add firebase_messaging [^7.0.0] to pubspec.yaml.
  2. Follow instruction on firebase_messaging plugin README section.
  3. Build on any real iOS device.
  4. Use following CURL in postman or anywhere to send notifications:
    curl --location --request POST 'https://fcm.googleapis.com/fcm/send' \
    --header 'Authorization: key=[WEB_SERVER_KEY_HERE]' \
    --header 'Content-Type: application/json' \
    --data-raw '{
    "to": "[FCM_TOKEN_HERE]",
    "data": {
        "click_action": "FLUTTER_NOTIFICATION_CLICK",
        "sound": "default",
        "body": "data body",
        "title": "data title",
        "content_available": true,
        "priority": "high",
        "route": "history",
        "url": "url"
    },
    "notification": {
        "sound": "default",
        "body": "notify body",
        "title": "notify title",
        "content_available": true,
        "priority": "high"
    }
    }'

Expected behavior

onMessage() is not called in foreground of real iOS devices but it get's called in simulator, onMessage() should be called in real iOS device too.


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 1.22.6, on macOS 11.2 20D64 darwin-x64, locale en-PK) [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3) [✓] Xcode - develop for iOS and macOS (Xcode 12.4) [✓] Android Studio (version 4.1) [✓] Connected device (1 available) • No issues found! ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` Dart SDK 2.10.5 Flutter SDK 1.22.6 roof 1.0.0+1 dependencies: - bubble 1.1.9+1 [flutter] - cached_network_image 2.5.0 [flutter flutter_cache_manager octo_image] - carousel_slider 2.3.4 [flutter] - chewie 0.9.10 [open_iconic_flutter video_player wakelock flutter] - cloud_firestore 0.14.4 [flutter meta quiver firebase_core firebase_core_platform_interface cloud_firestore_platform_interface cloud_firestore_web] - connectivity 2.0.2 [flutter meta connectivity_platform_interface connectivity_macos connectivity_for_web] - cupertino_icons 0.1.3 - dio 3.0.10 [http_parser path] - equatable 1.2.6 [collection meta] - firebase_analytics 6.3.0 [meta flutter firebase_core firebase_analytics_web firebase_analytics_platform_interface] - firebase_auth 0.18.4+1 [meta firebase_core firebase_core_platform_interface firebase_auth_platform_interface firebase_auth_web flutter] - firebase_core 0.5.3 [firebase_core_platform_interface flutter quiver meta firebase_core_web] - firebase_dynamic_links 0.6.3 [flutter firebase_core] - firebase_messaging 7.0.3 [meta flutter firebase_core] - firebase_storage 4.0.1 [flutter firebase_core] - flick_video_player 0.1.1 [flutter video_player provider wakelock] - flutter 0.0.0 [characters collection meta typed_data vector_math sky_engine] - flutter_bloc 6.1.2 [flutter bloc provider] - flutter_html 1.0.2 [html csslib css_colors video_player chewie webview_flutter chewie_audio flutter_svg flutter] - flutter_local_notifications 1.5.0+1 [flutter platform flutter_local_notifications_platform_interface] - flutter_localizations 0.0.0 [flutter intl characters collection meta path typed_data vector_math] - flutter_spinkit 4.1.2+1 [flutter] - geocoder 0.2.1 [meta flutter] - geolocator 5.3.2+2 [flutter meta equatable google_api_availability location_permissions vector_math] - google_maps_flutter 0.5.33 [flutter flutter_plugin_android_lifecycle google_maps_flutter_platform_interface] - image_cropper 1.3.1 [flutter] - image_picker 0.6.7+22 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface] - intercom_flutter 2.3.3 [flutter] - location 3.2.4 [flutter location_platform_interface location_web meta] - path_provider 1.6.27 [flutter path_provider_platform_interface path_provider_macos path_provider_linux path_provider_windows] - permission_handler 5.1.0+2 [flutter meta permission_handler_platform_interface] - photo_view 0.10.3 [flutter] - sembast 2.4.10 [meta path synchronized] - share 0.6.5+4 [meta mime flutter] - shared_preferences 0.5.12+4 [meta flutter shared_preferences_platform_interface shared_preferences_linux shared_preferences_macos shared_preferences_web shared_preferences_windows] - super_enum 0.4.2 [meta equatable] - toast 0.1.5 [flutter] - url_launcher 5.7.10 [flutter url_launcher_platform_interface url_launcher_web url_launcher_linux url_launcher_macos url_launcher_windows] - video_player 0.10.12+5 [meta video_player_platform_interface video_player_web flutter] - web_socket_channel 1.2.0 [async crypto stream_channel] - webview_flutter 0.3.24 [flutter] dev dependencies: - build_runner 1.10.0 [args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style glob graphs http_multi_server io js logging meta mime path pedantic pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml] - flutter_launcher_icons 0.8.1 [image args yaml path] - flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher meta source_span stream_channel string_scanner term_glyph typed_data] - super_enum_generator 0.5.0 [super_enum source_gen analyzer build code_builder dart_style] transitive dependencies: - _fe_analyzer_shared 7.0.0 [meta] - analyzer 0.39.17 [_fe_analyzer_shared args charcode cli_util collection convert crypto glob html meta package_config path pub_semver source_span watcher yaml] - archive 2.0.13 [crypto args path] - args 1.6.0 - async 2.5.0-nullsafety.1 [collection] - bloc 6.1.1 [meta] - boolean_selector 2.1.0-nullsafety.1 [source_span string_scanner] - build 1.3.0 [analyzer async convert crypto logging meta path glob] - build_config 0.4.2 [checked_yaml json_annotation meta path pubspec_parse yaml] - build_daemon 2.1.7 [built_collection built_value http_multi_server logging pedantic path pool shelf shelf_web_socket stream_transform watcher web_socket_channel] - build_resolvers 1.3.11 [analyzer build crypto graphs logging path package_config pub_semver] - build_runner_core 5.2.0 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta path package_config pedantic pool timing watcher yaml] - built_collection 4.3.2 [collection quiver] - built_value 7.1.0 [built_collection collection fixnum quiver] - characters 1.1.0-nullsafety.3 - charcode 1.2.0-nullsafety.1 - checked_yaml 1.0.4 [json_annotation source_span yaml] - chewie_audio 1.0.0+1 [open_iconic_flutter video_player screen flutter] - cli_util 0.2.0 [path] - clock 1.1.0-nullsafety.1 - cloud_firestore_platform_interface 2.2.1 [flutter meta collection firebase_core plugin_platform_interface] - cloud_firestore_web 0.2.1+2 [flutter flutter_web_plugins http_parser meta firebase_core firebase_core_web cloud_firestore_platform_interface js] - code_builder 3.6.0 [built_collection built_value collection matcher meta] - collection 1.15.0-nullsafety.3 - connectivity_for_web 0.3.1+4 [connectivity_platform_interface flutter_web_plugins flutter] - connectivity_macos 0.1.0+7 [flutter] - connectivity_platform_interface 1.0.6 [flutter meta plugin_platform_interface] - convert 2.1.1 [charcode typed_data] - crypto 2.1.5 [collection convert typed_data] - css_colors 1.0.2 [flutter] - csslib 0.16.2 [source_span] - dart_style 1.3.6 [analyzer args path source_span] - fake_async 1.2.0-nullsafety.1 [clock collection] - ffi 0.1.3 - file 5.2.1 [intl meta path] - firebase 7.3.3 [http http_parser js] - firebase_analytics_platform_interface 1.0.3 [flutter meta] - firebase_analytics_web 0.1.1 [flutter flutter_web_plugins firebase firebase_analytics_platform_interface meta] - firebase_auth_platform_interface 2.1.4 [flutter meta firebase_core plugin_platform_interface] - firebase_auth_web 0.3.2+3 [flutter flutter_web_plugins meta http_parser intl firebase_core firebase_core_web firebase_auth_platform_interface js] - firebase_core_platform_interface 2.1.0 [flutter meta plugin_platform_interface quiver] - firebase_core_web 0.2.1+1 [firebase_core_platform_interface flutter flutter_web_plugins meta js] - fixnum 0.10.11 - flutter_blurhash 0.5.0 [flutter meta] - flutter_cache_manager 2.1.1 [flutter path_provider uuid http path sqflite pedantic clock file rxdart image] - flutter_local_notifications_platform_interface 1.0.1 [flutter plugin_platform_interface] - flutter_plugin_android_lifecycle 1.0.11 [flutter] - flutter_svg 0.18.1 [path_drawing xml vector_math meta flutter] - flutter_web_plugins 0.0.0 [flutter characters collection meta typed_data vector_math] - glob 1.2.0 [async collection node_io path pedantic string_scanner] - google_api_availability 2.0.4 [flutter] - google_maps_flutter_platform_interface 1.2.0 [flutter meta plugin_platform_interface stream_transform collection] - graphs 0.2.0 - html 0.14.0+4 [csslib source_span] - http 0.12.2 [http_parser path pedantic] - http_multi_server 2.2.0 [async] - http_parser 3.1.4 [charcode collection source_span string_scanner typed_data] - image 2.1.19 [archive xml meta] - image_picker_platform_interface 1.1.6 [flutter meta http plugin_platform_interface] - intl 0.16.1 [path] - io 0.3.4 [charcode meta path string_scanner] - js 0.6.2 - json_annotation 3.1.1 - location_permissions 3.0.0+1 [flutter meta] - location_platform_interface 1.1.0 [flutter meta plugin_platform_interface] - location_web 1.0.1 [flutter flutter_web_plugins http_parser js location_platform_interface meta] - logging 0.11.4 - matcher 0.12.10-nullsafety.1 [stack_trace] - meta 1.3.0-nullsafety.3 - mime 0.9.7 - nested 0.0.4 [flutter] - node_interop 1.2.1 [js] - node_io 1.2.0 [file node_interop path] - octo_image 0.3.0 [flutter flutter_blurhash] - open_iconic_flutter 0.3.0 [flutter] - package_config 1.9.3 [path charcode] - path 1.8.0-nullsafety.1 - path_drawing 0.4.1+1 [vector_math meta path_parsing flutter] - path_parsing 0.1.4 [vector_math meta] - path_provider_linux 0.0.1+2 [path xdg_directories path_provider_platform_interface flutter] - path_provider_macos 0.0.4+8 [flutter] - path_provider_platform_interface 1.0.4 [flutter meta platform plugin_platform_interface] - path_provider_windows 0.0.4+3 [path_provider_platform_interface meta path flutter ffi win32] - pedantic 1.9.2 [meta] - permission_handler_platform_interface 2.0.2 [flutter meta plugin_platform_interface] - petitparser 3.1.0 [meta] - platform 2.2.1 - plugin_platform_interface 1.0.3 [meta] - pool 1.4.0 [async stack_trace] - process 3.0.13 [file intl meta path platform] - provider 4.3.3 [collection flutter nested] - pub_semver 1.4.4 [collection] - pubspec_parse 0.1.8 [checked_yaml json_annotation pub_semver yaml] - quiver 2.1.5 [matcher meta] - rxdart 0.25.0 - screen 0.0.5 [flutter] - shared_preferences_linux 0.0.2+4 [file flutter meta path path_provider_linux shared_preferences_platform_interface] - shared_preferences_macos 0.0.1+11 [shared_preferences_platform_interface flutter] - shared_preferences_platform_interface 1.0.4 [meta flutter] - shared_preferences_web 0.1.2+7 [shared_preferences_platform_interface flutter flutter_web_plugins meta] - shared_preferences_windows 0.0.2+3 [shared_preferences_platform_interface flutter file meta path path_provider_platform_interface path_provider_windows] - shelf 0.7.9 [async collection http_parser path stack_trace stream_channel] - shelf_web_socket 0.2.4+1 [shelf stream_channel web_socket_channel] - sky_engine 0.0.99 - source_gen 0.9.7+1 [analyzer async build dart_style glob meta path pedantic source_span] - source_span 1.8.0-nullsafety.2 [charcode collection path term_glyph] - sqflite 1.3.2+3 [flutter sqflite_common path] - sqflite_common 1.0.3+1 [synchronized path meta] - stack_trace 1.10.0-nullsafety.1 [path] - stream_channel 2.1.0-nullsafety.1 [async] - stream_transform 1.2.0 - string_scanner 1.1.0-nullsafety.1 [charcode source_span] - synchronized 2.2.0+2 - term_glyph 1.2.0-nullsafety.1 - test_api 0.2.19-nullsafety.2 [async boolean_selector collection meta path source_span stack_trace stream_channel string_scanner term_glyph matcher] - timing 0.1.1+3 [json_annotation] - typed_data 1.3.0-nullsafety.3 [collection] - url_launcher_linux 0.0.1+4 [flutter] - url_launcher_macos 0.0.1+9 [flutter] - url_launcher_platform_interface 1.0.9 [flutter meta plugin_platform_interface] - url_launcher_web 0.1.5+3 [url_launcher_platform_interface flutter flutter_web_plugins meta] - url_launcher_windows 0.0.1+3 [flutter] - uuid 2.2.2 [crypto convert] - vector_math 2.1.0-nullsafety.3 - video_player_platform_interface 2.2.0 [flutter meta] - video_player_web 0.1.4+1 [flutter flutter_web_plugins meta video_player_platform_interface] - wakelock 0.1.4+2 [flutter] - watcher 0.9.7+15 [async path pedantic] - win32 1.7.4+1 [ffi] - xdg_directories 0.1.2 [meta path process] - xml 4.5.1 [collection convert meta petitparser] - yaml 2.2.1 [charcode collection string_scanner source_span] ```

palancana commented 3 years ago

I have exactly the same issue! Hope someone can come up with a solution.

palancana commented 3 years ago

@Zulqurnain I upgraded firebase_messaging to ^8.0.0-dev.15 and now PN on a real device are working. This means, of course, I had to bump the version of firebase_core also to a compatible one (^0.7.0) and all the other Firebase plugins, do a flutter clean, a pod update and spend some time fixing issues.

Here's some documentation that helped me with the upgrade, because now the configure method is deprecated, so you will need to do some changes in your code.

https://firebase.flutter.dev/docs/messaging/usage/ https://firebase.flutter.dev/docs/migration/#common-upgrade-issues https://firebase.flutter.dev/docs/messaging/notifications#foreground-notifications

The good thing is that on iOS foreground notifications can now be activated with:

await _fcm.setForegroundNotificationPresentationOptions(
  alert: true, // Required to display a heads up notification
  badge: true,
  sound: true,
);

Before I needed to use an external package like Flushbar to mimic a notification in the foreground, so the update is more than welcome.

Happy coding!

Zulqurnain commented 3 years ago

@palancana your method didn't worked for me

markusaksli-nc commented 3 years ago

Hi @Zulqurnain What issues did you run into with the latest version? Thank you

Zulqurnain commented 3 years ago

I have mentioned all steps

On Mon, 22 Feb 2021, 6:22 pm Markus Aksli, notifications@github.com wrote:

Hi @Zulqurnain https://github.com/Zulqurnain What issues did you run into with the latest version? Thank you

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/FirebaseExtended/flutterfire/issues/5085#issuecomment-783369743, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABJ3TR5263TRUDERJA6JIBLTAJLB5ANCNFSM4X5BNBDA .

markusaksli-nc commented 3 years ago

I mean what issues did you run into with the latest non-nullsafety version firebase_messaging: ^8.0.0-dev.14?

The versions mentioned in your steps are outdated and are soon going to be replaced completely.

Zulqurnain commented 3 years ago

"I was not able to send notifications on real iOS device foreground mode" No matter what I do, what version I use

On Mon, 22 Feb 2021, 7:08 pm Markus Aksli, notifications@github.com wrote:

I mean what issues did you run into with the latest non-nullsafety version firebase_messaging: ^8.0.0-dev.14?

The versions mentioned in your steps are outdated and are soon going to be replaced completely.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/FirebaseExtended/flutterfire/issues/5085#issuecomment-783400838, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABJ3TRYBODFLZ2S24SGPZGLTAJQOVANCNFSM4X5BNBDA .

Zulqurnain commented 3 years ago

Any Update on this issue ?? I'm still not able get foreground notifications

markusaksli-nc commented 3 years ago

Could you try running the official example with firebase_messaging: ^8.0.0-dev.14?

Zulqurnain commented 3 years ago

Yes I have tried official example with my project it doesn't work



On Tue, 23 Feb 2021, 2:48 pm Markus Aksli, <notifications@github.com> wrote:

> Could you try running the official example
> <https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_messaging/firebase_messaging/example/lib>
> with firebase_messaging: ^8.0.0-dev.14?
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/FirebaseExtended/flutterfire/issues/5085#issuecomment-784044118>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/ABJ3TR5HBNAFS5NXKQSL2MDTAN2WZANCNFSM4X5BNBDA>
> .
>
Zulqurnain commented 3 years ago

I am posting everything I think is maybe wrong in my project but am not sure:

AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps
import Frames

@available(iOS 10.0, *)
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

    private var flutterResult: FlutterResult?

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GMSServices.provideAPIKey("[SOME_KEY_HERE]")

        let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController
        let methodChannel = FlutterMethodChannel(name: "flutter.native/helper", binaryMessenger: rootViewController.binaryMessenger)

        methodChannel.setMethodCallHandler({
            (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            if (call.method == "getCheckoutToken") {
                self.getCheckoutToken(result: result)
            }else if(call.method == "generateCheckoutToken"){
                let args = call.arguments as? [String: Any]
                let cardDetails =  args?["cardDetails"] as? [String: Any]

                self.generateCheckoutToken(result: result, cardDetails: cardDetails!)
            }else {
                result("Flutter method not implemented on iOS")
            }
        })

        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    var token=""
    private func getCheckoutToken(result: FlutterResult) {
        print("Get checkout Token: "+token)
        result(token)
    }

    private func generateCheckoutToken(result: FlutterResult, cardDetails: [String: Any]) {

            let checkoutAPIClient = CheckoutAPIClient(publicKey: "[SOME_KEY_HERE]", environment: .sandbox) // sandbox
            let cardUtils = CardUtils()

            /// verify card number
            let cardNumber = cardDetails["cardNo"] as? String
            let isCardValid = cardUtils.isValid(cardNumber: cardNumber!)

            if(isCardValid){

                // create the card token request
                let cardTokenRequest = CkoCardTokenRequest(number: cardNumber!,
                                                           expiryMonth: (cardDetails["expMonth"] as? String)!,
                                                           expiryYear: (cardDetails["expYear"] as? String)!,
                                                           cvv: (cardDetails["cvv"] as? String)!
                )

                // create the card token request
                checkoutAPIClient.createCardToken(card: cardTokenRequest,   successHandler:   { cardToken in
                    // success
                    print("Generated Token:"+cardToken.token)

                    self.token = cardToken.token

                },errorHandler:  { error in
                    // error
                    print("Error in Generating Token")
                    self.token=error.errorCodes[0]

                })
            }   else{
                result("ERROR_CARD")
            }

            print("Generating Token:"+token)
            result(token)
        }

}

app_firebase_notifications.dart

import 'dart:convert';
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:roof/db/local/shared_preferences.dart';
import 'package:roof/models/user_model.dart';
import 'package:roof/repository/firestore_repo.dart';
import 'package:roof/repository/misc_repository.dart';
import 'package:roof/repository/user_repository.dart';
import 'package:roof/ui/__shared/widgets/dialog/reward_dialog.dart';
import 'package:roof/ui/additional_payment/additional_payment_page.dart';

import 'app_routes.dart';
import 'helper/local_notification_helper.dart';

class AppFirebaseNotifications {
  /// Define a top-level named handler which background/terminated myMessages will
  /// call.
  ///
  /// To verify things are working, check out the native platform logs.
  Future<void> _firebaseMessagingBackgroundHandler(
      RemoteMessage myMessage) async {
    // If you're going to use other Firebase services in the background, such as Firestore,
    // make sure you call `initializeApp` before using other Firebase services.
    await Firebase.initializeApp();
    print('Handling a background myMessage ${myMessage.messageId}');
  }

  FirebaseMessaging _firebaseMessaging;
  FlutterLocalNotificationsPlugin _localNotificationsPlugin;
  LocalNotifications _localNotification = LocalNotifications();
  BuildContext context;

  init(BuildContext context) async {
    _firebaseMessaging = FirebaseMessaging.instance;

    _localNotificationsPlugin =
        await _localNotification.getNotificationPlugin(context);

    FirebaseMessaging.instance.setAutoInitEnabled(true);

    // Set the background messaging handler early on, as a named top-level function
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    _firebaseMessaging.getToken().then((fcmToken) async {
      print('fcmToken: $fcmToken');
      if (fcmToken != null) {
        final myFcmToken = await MySharedPreferences().getFCMToken();
        if (myFcmToken != fcmToken) {
          await MySharedPreferences().setFCMToken(fcmToken);
        }
        await MiscRepo().updateFCMToken({
          'action_type': 'add',
        });
        await MiscRepo().resetNotificationCount();
      }
    });

    _firebaseMessaging.getInitialMessage().then((RemoteMessage myMessage) {
      if (myMessage != null) {
        print("getInitialMessage = $myMessage");
        onNotify(myMessage);
      }
    });

    FirebaseMessaging.onMessage.listen((RemoteMessage myMessage) {
      print("onMessage = $myMessage");
      onNotify(myMessage);
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage myMessage) {
      print("onMessageOpenedApp = $myMessage");

      Navigator.pushNamed(context, myMessage.data["route"]);
      Map<String, dynamic> msg = createMap(myMessage.data);
      _navigateToScreen(context, msg);
    });
  }

  void onNotify(RemoteMessage remoteMessage) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ListTile(
          title: Text(remoteMessage.notification.title),
          subtitle: Text(remoteMessage.notification.body),
        ),
        actions: <Widget>[
          FlatButton(
            child: Text('Go'),
            onPressed: () =>
                Navigator.of(context).pushNamed(remoteMessage.data["route"]),
          ),
        ],
      ),
    );
    print('step 2');

    Map<String, dynamic> msg = createMap(remoteMessage.data);
    if (msg['route'].toLowerCase() == 'reward') {
      showRewardDialog(context, msg);
    } else if (msg['route'].toLowerCase() == 'morePaymentRequest') {
      additionalPaymentBottomSheet(
        context,
        remoteMessage.data['id'].toString(),
      );
    } else {
      _localNotification.loadData(msg);
      showOngoingNotification(
        _localNotificationsPlugin,
        title: msg['title'],
        body: msg['body'],
        id: 0,
      );
    }
  }

  Map<String, dynamic> createMap(Map<String, dynamic> myMessage) {
    Map<String, dynamic> params = jsonDecode(myMessage['params']);
    Map<String, dynamic> msg = Map();
    if (Platform.isIOS) {
      msg['title'] = myMessage['aps']['alert']['title'];
      msg['body'] = myMessage['aps']['alert']['body'];
      msg['id'] = params['id'];
      msg['route'] = myMessage['route'];

      if (msg['route'] == 'chatScreen' || msg['route'] == 'reward') {
        msg['bookingNo'] = params['booking_no'];
      }
      if (msg['route'] == 'reward') {
        msg['rewardAmount'] = params['reward_amount'];
      }
    }
    return msg;
  }
}

class LocalNotifications {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  Map<String, dynamic> myMessage;
  BuildContext context;

  getNotificationPlugin(context) async {
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    this.context = context;

    var initializationSettingsAndroid =
        AndroidInitializationSettings('mipmap/ic_launcher');

    var initializationSettingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: (
        int id,
        String title,
        String body,
        String payload,
      ) async {
        print(payload.toString());
        onSelectNotification(payload);
      },
    );

    flutterLocalNotificationsPlugin.initialize(
      InitializationSettings(
          android: initializationSettingsAndroid,
          iOS: initializationSettingsIOS,
          macOS: null),
      onSelectNotification: onSelectNotification,
    );

    FirebaseMessaging.instance.requestPermission();

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

    return flutterLocalNotificationsPlugin;
  }

  loadData(myMessage) {
    this.myMessage = myMessage;
    print('myMessage: $myMessage');
  }

  Future onSelectNotification(payload) async {
    print('myMessage: $myMessage');
    _navigateToScreen(context, myMessage);
  }
}

void _navigateToScreen(context, myMessage) async {
  String routeName = myMessage['route'];
  String bookingNo = myMessage['bookingNo'];
  await MiscRepo().resetNotificationCount();
  final UserModel user = await UserRepo().getUser();
  if (user != null && routeName != null) {
    print(routeName);
    if (routeName == 'chatScreen') {
      final response = await FirestoreRepo().getChatDoc(bookingNo);
      String userId = response['userId'];
      Map<String, dynamic> data = response['data'];

      Navigator.of(context).pushNamed(
        AppRoutes.chatScreen,
        arguments: {
          'data': data,
          'userId': userId,
        },
      );
    } else if ([
      'bookingDetails',
      'orderDetails',
      'rating',
    ].contains(routeName)) {
      Navigator.of(context).pushNamed(
        routeName,
        arguments: myMessage['id'].toString(),
      );
    } else if (routeName == 'reward') {
      Navigator.of(context).pushNamed(
        AppRoutes.wallet,
        arguments: false,
      );
      showRewardDialog(context, myMessage);
    } else if (routeName == 'morePaymentRequest') {
      additionalPaymentBottomSheet(
        context,
        myMessage['id'].toString(),
      );
    } else {
      Navigator.of(context).pushNamed(routeName);
    }
  }
}

AppFrameworkinfo.plist MinimumOSVersion: 9.0

Runner/Signing & Capabilities/ Running Modes [x] Background fetch [x] Remote Notifications [x] Background Processing Also added the Push Notification Capability

Runner SetUps [x] iOS Deployment Target: 13.6 [x] Deployment Info: iOS 13.6 checked [Phone, iPad]

Real Device Testing iPhone X 14.4

pubspec.yaml Already Provided details in post firebase_messaging can be any [^7.0.3] [^8.0.0-dev14] both doesn't work

Please Suppose code doesn't crash anywhere but Foreground notification don't work I don't think anything is wrong with my code here but if nothing is wrong with my code then it's plugin issue

markusaksli-nc commented 3 years ago

If you were following the setup for the old stable version then please double-check that you have carefully done everything in https://firebase.flutter.dev/docs/messaging/apple-integration

Zulqurnain commented 3 years ago

Yes I have followed exactly all the instructions mentioned in URL https://firebase.flutter.dev/docs/messaging/apple-integration

On Thu, 25 Feb 2021, 1:16 pm Markus Aksli, notifications@github.com wrote:

If you were following the setup for the old stable version then please double-check that you have carefully done everything in https://firebase.flutter.dev/docs/messaging/apple-integration

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/FirebaseExtended/flutterfire/issues/5085#issuecomment-785708777, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABJ3TR7ZLFZPWAXBIOID44TTAYBNNANCNFSM4X5BNBDA .

markusaksli-nc commented 3 years ago

Why have you disabled method swizzling? Are you using multiple notification services?

Zulqurnain commented 3 years ago

Doesn't matter if I turn swizzling on or off tried with both, not working

On Fri, 26 Feb 2021, 7:15 pm Markus Aksli, notifications@github.com wrote:

Why have you disabled method swizzling? Are you using multiple notification services?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/FirebaseExtended/flutterfire/issues/5085#issuecomment-786672426, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABJ3TR4HSOGD3UIMNDJOKYTTA6UHFANCNFSM4X5BNBDA .

markusaksli-nc commented 3 years ago

Does running the official example work fine on Android then? Is anything relevant logged in flutter run -v or device logs?

google-oss-bot commented 3 years ago

Hey @Zulqurnain. We need more information to resolve this issue but there hasn't been an update in 7 weekdays. I'm marking the issue as stale and if there are no new updates in the next 7 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

pratikbutani commented 3 years ago

Same here. I am testing notification on the postman using this link.

Its working on Android completely but not working on iOS.

google-oss-bot commented 3 years ago

Hey @Zulqurnain. We need more information to resolve this issue but there hasn't been an update in 7 weekdays. I'm marking the issue as stale and if there are no new updates in the next 7 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

google-oss-bot commented 3 years ago

Since there haven't been any recent updates here, I am going to close this issue.

@Zulqurnain if you're still experiencing this problem and want to continue the discussion just leave a comment here and we are happy to re-open this.