Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[firebase_messaging]: onMessage listener fires twice on iOS18 devices #13366

Closed
1 task done
justChris opened this issue Sep 19, 2024 · 44 comments · Fixed by #13572
Closed
1 task done

[firebase_messaging]: onMessage listener fires twice on iOS18 devices #13366

justChris opened this issue Sep 19, 2024 · 44 comments · Fixed by #13572
Assignees
Labels
blocked: customer-response Waiting for customer response, e.g. more information was requested. platform: ios Issues / PRs which are specifically for iOS. plugin: messaging type: bug Something isn't working

Comments

@justChris
Copy link

justChris commented Sep 19, 2024

Is there an existing issue for this?

  • I have searched the existing issues.

Which plugins are affected?

Messaging

Which platforms are affected?

iOS

Description

Since I upgraded to xcode16.0 and iOS18 the onMessage listener fires twice every time a message is received. This only happens with the onMessage listener, means when the app is in foreground. When the app is in background or terminated, this does NOT happen. And also this only happens on physical devices with iOS18. On devices with iOS17, the listener fires once per message, as expected.
I ensured that the listener is not subscribed multiple times, but still it fires twice.

Reproducing the issue

StreamSubscription? _streamSubscriptionOnMessage;

_streamSubscriptionOnMessage ??= FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  debugPrint('onMessage');
  _handleLocalNotification(message);
});

Firebase Core version

3.5.0

Flutter Version

3.24.3

Relevant Log Output

flutter doctor -v

[✓] Flutter (Channel stable, 3.24.3, on macOS 15.0 24A335 darwin-arm64, locale en-US)
    • Flutter version 3.24.3 on channel stable at /Users/chris/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 2663184aa7 (7 days ago), 2024-09-11 16:27:48 -0500
    • Engine revision 36335019a8
    • Dart version 3.5.3
    • DevTools version 2.37.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/chris/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 16.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 16A242d
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)

[✓] VS Code (version 1.93.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.96.0

[✓] Connected device (5 available)
    • Chris’s iPhone (mobile)         • 00008130-000970383EE0001C            • ios            • iOS 18.0 22A3354
    • iPhone 16 (mobile)              • 84AB7CC3-474C-4568-8A2E-0343B2B8C598 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-18-0 (simulator)
    • macOS (desktop)                 • macos                                • darwin-arm64   • macOS 15.0 24A335 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad                • darwin         • macOS 15.0 24A335 darwin-arm64
    • Chrome (web)                    • chrome                               • web-javascript • Google Chrome 128.0.6613.138

[✓] Network resources
    • All expected network resources are available.

• No issues found!

Flutter dependencies

Expand Flutter dependencies snippet
Dart SDK 3.5.3
Flutter SDK 3.24.3
cirqles 0.3.74+19

dependencies:
- async 2.11.0 [collection meta]
- badges 3.1.2 [flutter]
- cached_network_image 3.4.1 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image]
- cloud_firestore 5.4.2 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- cloud_functions 5.1.2 [cloud_functions_platform_interface cloud_functions_web firebase_core firebase_core_platform_interface flutter]
- cupertino_icons 1.0.8
- firebase_analytics 11.3.2 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter]
- firebase_auth 5.3.0 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 3.5.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_crashlytics 4.1.2 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace]
- firebase_database 11.1.3 [firebase_core firebase_core_platform_interface firebase_database_platform_interface firebase_database_web flutter]
- firebase_messaging 15.1.2 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_storage 12.3.1 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine]
- flutter_app_badge_control 0.0.1 [flutter plugin_platform_interface]
- flutter_cache_manager 3.4.1 [clock collection file flutter http path path_provider rxdart sqflite uuid]
- flutter_linkify 6.0.0 [flutter linkify]
- flutter_local_notifications 17.2.2 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_map 7.0.2 [async collection dart_earcut flutter http latlong2 logger meta polylabel proj4dart vector_math]
- flutter_native_splash 2.4.1 [args flutter flutter_web_plugins html image meta path universal_io xml yaml ansicolor]
- font_awesome_flutter 10.7.0 [flutter]
- geocoding 3.0.0 [flutter geocoding_platform_interface geocoding_android geocoding_ios]
- geolocator 13.0.1 [flutter geolocator_platform_interface geolocator_android geolocator_apple geolocator_web geolocator_windows]
- hive 2.2.3 [meta crypto]
- hive_flutter 1.1.0 [flutter hive path_provider path]
- html 0.15.4 [csslib source_span]
- http 1.2.2 [async http_parser meta web]
- image 4.2.0 [archive meta xml]
- image_cropper 8.0.2 [flutter image_cropper_platform_interface image_cropper_for_web]
- image_picker 1.1.2 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_linux image_picker_macos image_picker_platform_interface image_picker_windows]
- intl 0.19.0 [clock meta path]
- latlong2 0.9.1 [intl]
- provider 6.1.2 [collection flutter nested]
- rxdart 0.28.0
- shimmer 3.0.0 [flutter]
- smooth_page_indicator 1.2.0+3 [flutter]
- timeago 3.7.0 [intl]
- transparent_image 2.0.1
- url_launcher 6.3.0 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- uuid 4.5.0 [crypto sprintf meta fixnum]

dev dependencies:
- build_runner 2.4.12 [analyzer args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml]
- flutter_lints 4.0.0 [lints]
- flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math leak_tracker_flutter_testing async boolean_selector characters collection leak_tracker leak_tracker_testing material_color_utilities meta source_span stream_channel string_scanner term_glyph vm_service]
- hive_generator 2.0.1 [build source_gen hive analyzer source_helper]

dependency overrides:
- build_runner 2.4.12 [analyzer args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml]
- font_awesome_flutter 10.7.0 [flutter]
- hive_generator 2.0.1 [build source_gen hive analyzer source_helper]

transitive dependencies:
- _fe_analyzer_shared 72.0.0 [meta]
- _flutterfire_internals 1.3.43 [collection firebase_core firebase_core_platform_interface flutter meta]
- _macros 0.3.2
- analyzer 6.7.0 [_fe_analyzer_shared collection convert crypto glob macros meta package_config path pub_semver source_span watcher yaml]
- ansicolor 2.0.3
- archive 3.6.1 [crypto path]
- args 2.5.0
- boolean_selector 2.1.1 [source_span string_scanner]
- build 2.4.1 [analyzer async convert crypto glob logging meta package_config path]
- build_config 1.1.1 [checked_yaml json_annotation path pubspec_parse yaml]
- build_daemon 4.0.2 [built_collection built_value crypto http_multi_server logging path pool shelf shelf_web_socket stream_transform watcher web_socket_channel]
- build_resolvers 2.4.2 [analyzer async build collection convert crypto graphs logging package_config path pool pub_semver stream_transform yaml]
- build_runner_core 7.3.2 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta package_config path pool timing watcher yaml]
- built_collection 5.1.1
- built_value 8.9.2 [built_collection collection fixnum meta]
- cached_network_image_platform_interface 4.1.1 [flutter flutter_cache_manager]
- cached_network_image_web 1.3.1 [cached_network_image_platform_interface flutter flutter_cache_manager web]
- characters 1.3.0
- checked_yaml 2.0.3 [json_annotation source_span yaml]
- clock 1.1.1
- cloud_firestore_platform_interface 6.4.2 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 4.3.1 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins]
- cloud_functions_platform_interface 5.5.36 [firebase_core flutter meta plugin_platform_interface]
- cloud_functions_web 4.10.1 [cloud_functions_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins]
- code_builder 4.10.0 [built_collection built_value collection matcher meta]
- collection 1.18.0
- convert 3.1.1 [typed_data]
- cross_file 0.3.4+2 [meta web]
- crypto 3.0.5 [typed_data]
- csslib 1.0.0 [source_span]
- dart_earcut 1.1.0
- dart_style 2.3.7 [analyzer args collection package_config path pub_semver source_span]
- dbus 0.7.10 [args ffi meta xml]
- fake_async 1.3.1 [clock collection]
- ffi 2.1.3
- file 7.0.0 [meta path]
- file_selector_linux 0.9.2+1 [cross_file file_selector_platform_interface flutter]
- file_selector_macos 0.9.4 [cross_file file_selector_platform_interface flutter]
- file_selector_platform_interface 2.6.2 [cross_file flutter http plugin_platform_interface]
- file_selector_windows 0.9.3+2 [cross_file file_selector_platform_interface flutter]
- firebase_analytics_platform_interface 4.2.4 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_analytics_web 0.5.10+1 [_flutterfire_internals firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins]
- firebase_auth_platform_interface 7.4.6 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 5.13.1 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser meta web]
- firebase_core_platform_interface 5.3.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.18.1 [firebase_core_platform_interface flutter flutter_web_plugins meta web]
- firebase_crashlytics_platform_interface 3.6.43 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_platform_interface 0.2.5+43 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_web 0.2.6+1 [collection firebase_core firebase_core_web firebase_database_platform_interface flutter flutter_web_plugins]
- firebase_messaging_platform_interface 4.5.45 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.9.1 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins meta web]
- firebase_storage_platform_interface 5.1.30 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_storage_web 3.10.1 [_flutterfire_internals async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http meta web]
- fixnum 1.1.0
- flutter_local_notifications_linux 4.0.1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories]
- flutter_local_notifications_platform_interface 7.2.0 [flutter plugin_platform_interface]
- flutter_plugin_android_lifecycle 2.0.22 [flutter]
- flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math]
- frontend_server_client 4.0.0 [async path]
- geocoding_android 3.3.1 [flutter geocoding_platform_interface]
- geocoding_ios 3.0.1 [flutter geocoding_platform_interface]
- geocoding_platform_interface 3.2.0 [flutter meta plugin_platform_interface]
- geolocator_android 4.6.1 [flutter geolocator_platform_interface meta uuid]
- geolocator_apple 2.3.7 [flutter geolocator_platform_interface]
- geolocator_platform_interface 4.2.4 [flutter plugin_platform_interface vector_math meta]
- geolocator_web 4.1.1 [flutter flutter_web_plugins geolocator_platform_interface web]
- geolocator_windows 0.2.3 [flutter geolocator_platform_interface]
- glob 2.1.2 [async collection file path string_scanner]
- graphs 2.3.2 [collection]
- http_multi_server 3.2.1 [async]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- image_cropper_for_web 6.0.2 [flutter flutter_web_plugins image_cropper_platform_interface web]
- image_cropper_platform_interface 7.0.0 [flutter plugin_platform_interface http]
- image_picker_android 0.8.12+13 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 3.0.5 [flutter flutter_web_plugins image_picker_platform_interface mime web]
- image_picker_ios 0.8.12 [flutter image_picker_platform_interface]
- image_picker_linux 0.2.1+1 [file_selector_linux file_selector_platform_interface flutter image_picker_platform_interface]
- image_picker_macos 0.2.1+1 [file_selector_macos file_selector_platform_interface flutter image_picker_platform_interface]
- image_picker_platform_interface 2.10.0 [cross_file flutter http plugin_platform_interface]
- image_picker_windows 0.2.1+1 [file_selector_platform_interface file_selector_windows flutter image_picker_platform_interface]
- io 1.0.4 [meta path string_scanner]
- js 0.7.1
- json_annotation 4.9.0 [meta]
- leak_tracker 10.0.5 [clock collection meta path vm_service]
- leak_tracker_flutter_testing 3.0.5 [flutter leak_tracker leak_tracker_testing matcher meta]
- leak_tracker_testing 3.0.1 [leak_tracker matcher meta]
- linkify 5.0.0
- lints 4.0.0
- lists 1.0.1 [meta]
- logger 2.4.0
- logging 1.2.0
- macros 0.1.2-main.4 [_macros]
- matcher 0.12.16+1 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.11.1 [collection]
- meta 1.15.0
- mgrs_dart 2.0.0 [unicode]
- mime 1.0.6
- nested 1.0.0 [flutter]
- octo_image 2.1.0 [flutter]
- package_config 2.1.0 [path]
- path 1.9.0
- path_provider 2.1.4 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows]
- path_provider_android 2.2.10 [flutter path_provider_platform_interface]
- path_provider_foundation 2.4.0 [flutter path_provider_platform_interface]
- path_provider_linux 2.2.1 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_platform_interface 2.1.2 [flutter platform plugin_platform_interface]
- path_provider_windows 2.3.0 [ffi flutter path path_provider_platform_interface]
- petitparser 6.0.2 [meta]
- platform 3.1.5
- plugin_platform_interface 2.1.8 [meta]
- polylabel 1.0.1 [collection]
- pool 1.5.1 [async stack_trace]
- proj4dart 2.1.0 [mgrs_dart wkt_parser meta]
- pub_semver 2.1.4 [collection meta]
- pubspec_parse 1.3.0 [checked_yaml collection json_annotation pub_semver yaml]
- shelf 1.4.1 [async collection http_parser path stack_trace stream_channel]
- shelf_web_socket 2.0.0 [shelf stream_channel web_socket_channel]
- sky_engine 0.0.99
- source_gen 1.5.0 [analyzer async build dart_style glob path source_span yaml]
- source_helper 1.3.4 [analyzer collection source_gen]
- source_span 1.10.0 [collection path term_glyph]
- sprintf 7.0.0
- sqflite 2.3.3+1 [flutter sqflite_common path]
- sqflite_common 2.5.4+3 [synchronized path meta]
- stack_trace 1.11.1 [path]
- stream_channel 2.1.2 [async]
- stream_transform 2.1.0
- string_scanner 1.2.0 [source_span]
- synchronized 3.3.0+2
- term_glyph 1.2.1
- test_api 0.7.2 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph]
- timezone 0.9.4 [path]
- timing 1.0.1 [json_annotation]
- typed_data 1.3.2 [collection]
- unicode 0.3.1 [lists]
- universal_io 2.2.2 [collection meta typed_data]
- url_launcher_android 6.3.10 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.3.1 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.2.0 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.2.0 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.3.2 [flutter plugin_platform_interface]
- url_launcher_web 2.3.3 [flutter flutter_web_plugins url_launcher_platform_interface web]
- url_launcher_windows 3.1.2 [flutter url_launcher_platform_interface]
- vector_math 2.1.4
- vm_service 14.2.5
- watcher 1.1.0 [async path]
- web 1.0.0
- web_socket 0.1.6 [web]
- web_socket_channel 3.0.1 [async crypto stream_channel web web_socket]
- wkt_parser 2.0.0
- xdg_directories 1.0.4 [meta path]
- xml 6.5.0 [collection meta petitparser]
- yaml 3.1.2 [collection source_span string_scanner]

Additional context and comments

No response

@justChris justChris added Needs Attention This issue needs maintainer attention. type: bug Something isn't working labels Sep 19, 2024
@SelaseKay SelaseKay added plugin: messaging platform: ios Issues / PRs which are specifically for iOS. labels Sep 19, 2024
@hohoins
Copy link

hohoins commented Sep 19, 2024

I'm having the same problem.
onMessage is triggered twice in iOS18.
This seems to be a critical issue.
Please check quickly.
For reference, there was no problem in iOS17.

[Environment]
flutter: 3.13.9
os: ios18
firebase_messaging: ^14.7.10
firebase_core: ^2.24.2
firebase_analytics: ^10.8.0
firebase_crashlytics: ^3.4.9
firebase_remote_config: ^4.3.8

@soumyajitdas365
Copy link

Is there an existing issue for this?

  • I have searched the existing issues.

Which plugins are affected?

Messaging

Which platforms are affected?

iOS

Description

Since I upgraded to xcode16.0 and iOS18 the onMessage listener fires twice every time a message is received. This only happens with the onMessage listener, means when the app is in foreground. When the app is in background or terminated, this does NOT happen. And also this only happens on physical devices with iOS18. On devices with iOS17, the listener fires once per message, as expected.
I ensured that the listener is not subscribed multiple times, but still it fires twice.

Reproducing the issue

StreamSubscription? _streamSubscriptionOnMessage;

_streamSubscriptionOnMessage ??= FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  debugPrint('onMessage');
  _handleLocalNotification(message);
});

Firebase Core version

3.5.0

Flutter Version

3.24.3

Relevant Log Output

flutter doctor -v

[✓] Flutter (Channel stable, 3.24.3, on macOS 15.0 24A335 darwin-arm64, locale en-US)
    • Flutter version 3.24.3 on channel stable at /Users/chris/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 2663184aa7 (7 days ago), 2024-09-11 16:27:48 -0500
    • Engine revision 36335019a8
    • Dart version 3.5.3
    • DevTools version 2.37.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/chris/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 16.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 16A242d
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)

[✓] VS Code (version 1.93.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.96.0

[✓] Connected device (5 available)
    • Chris’s iPhone (mobile)         • 00008130-000970383EE0001C            • ios            • iOS 18.0 22A3354
    • iPhone 16 (mobile)              • 84AB7CC3-474C-4568-8A2E-0343B2B8C598 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-18-0 (simulator)
    • macOS (desktop)                 • macos                                • darwin-arm64   • macOS 15.0 24A335 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad                • darwin         • macOS 15.0 24A335 darwin-arm64
    • Chrome (web)                    • chrome                               • web-javascript • Google Chrome 128.0.6613.138

[✓] Network resources
    • All expected network resources are available.

• No issues found!

Flutter dependencies

Expand Flutter dependencies snippet
Dart SDK 3.5.3
Flutter SDK 3.24.3
cirqles 0.3.74+19

dependencies:
- async 2.11.0 [collection meta]
- badges 3.1.2 [flutter]
- cached_network_image 3.4.1 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image]
- cloud_firestore 5.4.2 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- cloud_functions 5.1.2 [cloud_functions_platform_interface cloud_functions_web firebase_core firebase_core_platform_interface flutter]
- cupertino_icons 1.0.8
- firebase_analytics 11.3.2 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter]
- firebase_auth 5.3.0 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 3.5.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_crashlytics 4.1.2 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace]
- firebase_database 11.1.3 [firebase_core firebase_core_platform_interface firebase_database_platform_interface firebase_database_web flutter]
- firebase_messaging 15.1.2 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_storage 12.3.1 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine]
- flutter_app_badge_control 0.0.1 [flutter plugin_platform_interface]
- flutter_cache_manager 3.4.1 [clock collection file flutter http path path_provider rxdart sqflite uuid]
- flutter_linkify 6.0.0 [flutter linkify]
- flutter_local_notifications 17.2.2 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_map 7.0.2 [async collection dart_earcut flutter http latlong2 logger meta polylabel proj4dart vector_math]
- flutter_native_splash 2.4.1 [args flutter flutter_web_plugins html image meta path universal_io xml yaml ansicolor]
- font_awesome_flutter 10.7.0 [flutter]
- geocoding 3.0.0 [flutter geocoding_platform_interface geocoding_android geocoding_ios]
- geolocator 13.0.1 [flutter geolocator_platform_interface geolocator_android geolocator_apple geolocator_web geolocator_windows]
- hive 2.2.3 [meta crypto]
- hive_flutter 1.1.0 [flutter hive path_provider path]
- html 0.15.4 [csslib source_span]
- http 1.2.2 [async http_parser meta web]
- image 4.2.0 [archive meta xml]
- image_cropper 8.0.2 [flutter image_cropper_platform_interface image_cropper_for_web]
- image_picker 1.1.2 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_linux image_picker_macos image_picker_platform_interface image_picker_windows]
- intl 0.19.0 [clock meta path]
- latlong2 0.9.1 [intl]
- provider 6.1.2 [collection flutter nested]
- rxdart 0.28.0
- shimmer 3.0.0 [flutter]
- smooth_page_indicator 1.2.0+3 [flutter]
- timeago 3.7.0 [intl]
- transparent_image 2.0.1
- url_launcher 6.3.0 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- uuid 4.5.0 [crypto sprintf meta fixnum]

dev dependencies:
- build_runner 2.4.12 [analyzer args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml]
- flutter_lints 4.0.0 [lints]
- flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math leak_tracker_flutter_testing async boolean_selector characters collection leak_tracker leak_tracker_testing material_color_utilities meta source_span stream_channel string_scanner term_glyph vm_service]
- hive_generator 2.0.1 [build source_gen hive analyzer source_helper]

dependency overrides:
- build_runner 2.4.12 [analyzer args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml]
- font_awesome_flutter 10.7.0 [flutter]
- hive_generator 2.0.1 [build source_gen hive analyzer source_helper]

transitive dependencies:
- _fe_analyzer_shared 72.0.0 [meta]
- _flutterfire_internals 1.3.43 [collection firebase_core firebase_core_platform_interface flutter meta]
- _macros 0.3.2
- analyzer 6.7.0 [_fe_analyzer_shared collection convert crypto glob macros meta package_config path pub_semver source_span watcher yaml]
- ansicolor 2.0.3
- archive 3.6.1 [crypto path]
- args 2.5.0
- boolean_selector 2.1.1 [source_span string_scanner]
- build 2.4.1 [analyzer async convert crypto glob logging meta package_config path]
- build_config 1.1.1 [checked_yaml json_annotation path pubspec_parse yaml]
- build_daemon 4.0.2 [built_collection built_value crypto http_multi_server logging path pool shelf shelf_web_socket stream_transform watcher web_socket_channel]
- build_resolvers 2.4.2 [analyzer async build collection convert crypto graphs logging package_config path pool pub_semver stream_transform yaml]
- build_runner_core 7.3.2 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta package_config path pool timing watcher yaml]
- built_collection 5.1.1
- built_value 8.9.2 [built_collection collection fixnum meta]
- cached_network_image_platform_interface 4.1.1 [flutter flutter_cache_manager]
- cached_network_image_web 1.3.1 [cached_network_image_platform_interface flutter flutter_cache_manager web]
- characters 1.3.0
- checked_yaml 2.0.3 [json_annotation source_span yaml]
- clock 1.1.1
- cloud_firestore_platform_interface 6.4.2 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 4.3.1 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins]
- cloud_functions_platform_interface 5.5.36 [firebase_core flutter meta plugin_platform_interface]
- cloud_functions_web 4.10.1 [cloud_functions_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins]
- code_builder 4.10.0 [built_collection built_value collection matcher meta]
- collection 1.18.0
- convert 3.1.1 [typed_data]
- cross_file 0.3.4+2 [meta web]
- crypto 3.0.5 [typed_data]
- csslib 1.0.0 [source_span]
- dart_earcut 1.1.0
- dart_style 2.3.7 [analyzer args collection package_config path pub_semver source_span]
- dbus 0.7.10 [args ffi meta xml]
- fake_async 1.3.1 [clock collection]
- ffi 2.1.3
- file 7.0.0 [meta path]
- file_selector_linux 0.9.2+1 [cross_file file_selector_platform_interface flutter]
- file_selector_macos 0.9.4 [cross_file file_selector_platform_interface flutter]
- file_selector_platform_interface 2.6.2 [cross_file flutter http plugin_platform_interface]
- file_selector_windows 0.9.3+2 [cross_file file_selector_platform_interface flutter]
- firebase_analytics_platform_interface 4.2.4 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_analytics_web 0.5.10+1 [_flutterfire_internals firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins]
- firebase_auth_platform_interface 7.4.6 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 5.13.1 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser meta web]
- firebase_core_platform_interface 5.3.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.18.1 [firebase_core_platform_interface flutter flutter_web_plugins meta web]
- firebase_crashlytics_platform_interface 3.6.43 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_platform_interface 0.2.5+43 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_web 0.2.6+1 [collection firebase_core firebase_core_web firebase_database_platform_interface flutter flutter_web_plugins]
- firebase_messaging_platform_interface 4.5.45 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.9.1 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins meta web]
- firebase_storage_platform_interface 5.1.30 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_storage_web 3.10.1 [_flutterfire_internals async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http meta web]
- fixnum 1.1.0
- flutter_local_notifications_linux 4.0.1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories]
- flutter_local_notifications_platform_interface 7.2.0 [flutter plugin_platform_interface]
- flutter_plugin_android_lifecycle 2.0.22 [flutter]
- flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math]
- frontend_server_client 4.0.0 [async path]
- geocoding_android 3.3.1 [flutter geocoding_platform_interface]
- geocoding_ios 3.0.1 [flutter geocoding_platform_interface]
- geocoding_platform_interface 3.2.0 [flutter meta plugin_platform_interface]
- geolocator_android 4.6.1 [flutter geolocator_platform_interface meta uuid]
- geolocator_apple 2.3.7 [flutter geolocator_platform_interface]
- geolocator_platform_interface 4.2.4 [flutter plugin_platform_interface vector_math meta]
- geolocator_web 4.1.1 [flutter flutter_web_plugins geolocator_platform_interface web]
- geolocator_windows 0.2.3 [flutter geolocator_platform_interface]
- glob 2.1.2 [async collection file path string_scanner]
- graphs 2.3.2 [collection]
- http_multi_server 3.2.1 [async]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- image_cropper_for_web 6.0.2 [flutter flutter_web_plugins image_cropper_platform_interface web]
- image_cropper_platform_interface 7.0.0 [flutter plugin_platform_interface http]
- image_picker_android 0.8.12+13 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 3.0.5 [flutter flutter_web_plugins image_picker_platform_interface mime web]
- image_picker_ios 0.8.12 [flutter image_picker_platform_interface]
- image_picker_linux 0.2.1+1 [file_selector_linux file_selector_platform_interface flutter image_picker_platform_interface]
- image_picker_macos 0.2.1+1 [file_selector_macos file_selector_platform_interface flutter image_picker_platform_interface]
- image_picker_platform_interface 2.10.0 [cross_file flutter http plugin_platform_interface]
- image_picker_windows 0.2.1+1 [file_selector_platform_interface file_selector_windows flutter image_picker_platform_interface]
- io 1.0.4 [meta path string_scanner]
- js 0.7.1
- json_annotation 4.9.0 [meta]
- leak_tracker 10.0.5 [clock collection meta path vm_service]
- leak_tracker_flutter_testing 3.0.5 [flutter leak_tracker leak_tracker_testing matcher meta]
- leak_tracker_testing 3.0.1 [leak_tracker matcher meta]
- linkify 5.0.0
- lints 4.0.0
- lists 1.0.1 [meta]
- logger 2.4.0
- logging 1.2.0
- macros 0.1.2-main.4 [_macros]
- matcher 0.12.16+1 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.11.1 [collection]
- meta 1.15.0
- mgrs_dart 2.0.0 [unicode]
- mime 1.0.6
- nested 1.0.0 [flutter]
- octo_image 2.1.0 [flutter]
- package_config 2.1.0 [path]
- path 1.9.0
- path_provider 2.1.4 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows]
- path_provider_android 2.2.10 [flutter path_provider_platform_interface]
- path_provider_foundation 2.4.0 [flutter path_provider_platform_interface]
- path_provider_linux 2.2.1 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_platform_interface 2.1.2 [flutter platform plugin_platform_interface]
- path_provider_windows 2.3.0 [ffi flutter path path_provider_platform_interface]
- petitparser 6.0.2 [meta]
- platform 3.1.5
- plugin_platform_interface 2.1.8 [meta]
- polylabel 1.0.1 [collection]
- pool 1.5.1 [async stack_trace]
- proj4dart 2.1.0 [mgrs_dart wkt_parser meta]
- pub_semver 2.1.4 [collection meta]
- pubspec_parse 1.3.0 [checked_yaml collection json_annotation pub_semver yaml]
- shelf 1.4.1 [async collection http_parser path stack_trace stream_channel]
- shelf_web_socket 2.0.0 [shelf stream_channel web_socket_channel]
- sky_engine 0.0.99
- source_gen 1.5.0 [analyzer async build dart_style glob path source_span yaml]
- source_helper 1.3.4 [analyzer collection source_gen]
- source_span 1.10.0 [collection path term_glyph]
- sprintf 7.0.0
- sqflite 2.3.3+1 [flutter sqflite_common path]
- sqflite_common 2.5.4+3 [synchronized path meta]
- stack_trace 1.11.1 [path]
- stream_channel 2.1.2 [async]
- stream_transform 2.1.0
- string_scanner 1.2.0 [source_span]
- synchronized 3.3.0+2
- term_glyph 1.2.1
- test_api 0.7.2 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph]
- timezone 0.9.4 [path]
- timing 1.0.1 [json_annotation]
- typed_data 1.3.2 [collection]
- unicode 0.3.1 [lists]
- universal_io 2.2.2 [collection meta typed_data]
- url_launcher_android 6.3.10 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.3.1 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.2.0 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.2.0 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.3.2 [flutter plugin_platform_interface]
- url_launcher_web 2.3.3 [flutter flutter_web_plugins url_launcher_platform_interface web]
- url_launcher_windows 3.1.2 [flutter url_launcher_platform_interface]
- vector_math 2.1.4
- vm_service 14.2.5
- watcher 1.1.0 [async path]
- web 1.0.0
- web_socket 0.1.6 [web]
- web_socket_channel 3.0.1 [async crypto stream_channel web web_socket]
- wkt_parser 2.0.0
- xdg_directories 1.0.4 [meta path]
- xml 6.5.0 [collection meta petitparser]
- yaml 3.1.2 [collection source_span string_scanner]

Additional context and comments

No response

Hello,

Is it working fine in the android application? Can you tell me?

@justChris
Copy link
Author

justChris commented Sep 20, 2024

On Android it is working as expected. @soumyajitdas365

@hohoins
Copy link

hohoins commented Sep 20, 2024

@soumyajitdas365
I think it might be a problem with the firebase_messaging package.
When onMessage is received twice, the RemoteMessage.messageId of the 2 messages is the same.
The messageId should be a unique value. But isn't it a bug that the same messageId value occurs twice?

@soumyajitdas365
Copy link

soumyajitdas365 commented Sep 20, 2024

On Android it is working as expected.
@justChris

Can you help by providing the code for Android?
Because I'm struggling with Android and for iOS I'm facing the same issue as yours

@Tom3652
Copy link

Tom3652 commented Sep 20, 2024

I have faced the same issue today after upgrading to iOS 18.
I am saving a local list of the RemoteMessage.messageId as @hohoins mentionned to avoid running the code twice for now as a workaround, since it's indeed the same RemoteMessage.messageId that is thrown.

@justChris
Copy link
Author

justChris commented Sep 21, 2024

On Android it is working as expected.
@justChris

Can you help by providing the code for Android?
Because I'm struggling with Android and for iOS I'm facing the same issue as yours

@soumyajitdas365

Please refer to the official documentation https://firebase.google.com/docs/flutter/setup?platform=android

@justChris
Copy link
Author

I have faced the same issue today after upgrading to iOS 18.

I am saving a local list of the RemoteMessage.messageId as @hohoins mentionned to avoid running the code twice for now as a workaround, since it's indeed the same RemoteMessage.messageId that is thrown.

@Tom3652

Thanks for the insight. I will test that myself.
In the function logs I can see that the message is only sent once. But the listener gets fired twice. So I strongly assume that the issue is in the local library.

@Tom3652
Copy link

Tom3652 commented Sep 21, 2024

Yes indeed in my function log i also see that the notification is sent once and i have tried to sent it from my local machine using the firebase admin sdk, it doesn't send 2 notifications server-side.

Besides, the client listener is only fired once on my android device using and on my iOS 17.5.1 device it fires only once the client listener 🙏🏻

@nukeolay
Copy link

Same problem here. I upgraded to Xcode 16.0 and iOS18 and now the onMessage listener fires twice every time a message is received.
firebase_core - 3.5.0, firebase_messaging: ^15.1.2, Flutter Version - 3.24.3
Android works fine

@xBLACKICEx
Copy link

Same problem, I would like to know which version is available for the current situation?

@Alabfa
Copy link

Alabfa commented Sep 23, 2024

Same problem here, I wish I found this earlier because I was struggling for 13 hours thinking the problem in my code.

@justChris
Copy link
Author

Since this is only happening when the app is in foreground, it would be better to save the message ids to an array at runtime. This way you can check whether the corresponding message id is already existing in the array and thus already been processed. Then you can just ignore any further messages with the same id.

@SelaseKay
Copy link
Contributor

Hi @justChris , thanks for submitting this issue. I'm going to upgrade my iOS to version 18 since it's prerequisite to reproduce this issue. I'd provide feedback on my findings.

@linsendidi
Copy link

Also facing the same issue. Did some tests from my side.

Flutter version:
3.22.3

Firebase dependencies:

firebase_core: 3.3.0
firebase_messaging: 15.0.4

Devices Tested:

iOS 18.0 (iPhone 15 Pro): Messaging received twice when app is in the foreground.
iOS 17.7 (iPhone 12 Pro): Works as expected.
Android 13 (Pixel 4 XL): Works as expected.
Android 14 (Galaxy S23 Ultra): Works as expected.

@SelaseKay
Copy link
Contributor

Hi @justChris , I'm able to reproduce this issue on iOS 18.

@SerdarNur
Copy link

Hi guys, we have the same issue. We are receiving on iOS 18 devices events onMessage twice. On iOS 17 device with the same code base it is only fired once. Very critical bug.

@nukeolay
Copy link

I have faced the same issue today after upgrading to iOS 18.
I am saving a local list of the RemoteMessage.messageId as @hohoins mentionned to avoid running the code twice for now as a workaround, since it's indeed the same RemoteMessage.messageId that is thrown.

Yes, I think it's the best way to deal with the bug until we get a fixed version of Firebase lib.
In our project we use this code:

final _recievedMessages = <String>[];

void _onMessageHandler(RemoteMessage message) {
final messageId = message.messageId;
  if (_recievedMessages.contains(messageId)) {
    return;
  }
  if (messageId != null) {
    _recievedMessages.add(messageId);
  }

  // your message handle logic here
}

StreamSubscription? _onMessageSubscription;

_onMessageSubscription ??= FirebaseMessaging.onMessage.listen(_onMessageHandler);

@ovidiuadorian-yonder
Copy link

For me onMessage.listen is not invoked, it's a really big issue on IOS18

@Lyokone Lyokone self-assigned this Oct 2, 2024
@Lyokone
Copy link
Contributor

Lyokone commented Oct 2, 2024

Hello all, we are investigating this issue, but it seems to be a bug in iOS 18 not directly related to FlutterFire: https://forums.developer.apple.com/forums/thread/761597
I'll dig a bit more to see what can be done to mitigate this.

@pintu-elaunch
Copy link

+1

@justChris
Copy link
Author

Are there any news on that by now?

@Yousef-Alabdulhadi
Copy link

This bug made me think I lost my mind, any updates on the fix?

@gramirezmil
Copy link

Me too, please help, almost lost my job

@Altrozero
Copy link

Was having the same issue, after updating to iOS 18.1 on device the issue stopped. Given iOS 18.0 will be around for a while we've put in a check to save the message id's and not show any duplicates.

@cmorsucci
Copy link

Was having the same issue, after updating to iOS 18.1 on device the issue stopped. Given iOS 18.0 will be around for a while we've put in a check to save the message id's and not show any duplicates.

Unfortunately I tried with iOS 18.1 and the bug persists

@sth0409
Copy link

sth0409 commented Oct 30, 2024

This is how I solved it temporarily. I hope the official will optimize it as soon as possible.

FirebaseMessaging.onMessage.listen((RemoteMessage message) async { debugPrint('Got a message whilst in the foreground!'); debugPrint('Message data: ${message.toMap()}'); if (message.data.isNotEmpty) { if (message.messageId == null || message.messageId!.isEmpty) { return; } if (messageIdOld == message.messageId) { debugPrint('messageIdOld == messageId return'); return; } messageIdOld = message.messageId; }}

@sth0409
Copy link

sth0409 commented Oct 30, 2024

This is how I solved it temporarily. I hope the official will optimize it as soon as possible.

 FirebaseMessaging.onMessage.listen((RemoteMessage message) async {

  debugPrint('Got a message whilst in the foreground!');
  debugPrint('Message data: ${message.toMap()}');
  
  if (message.data.isNotEmpty) {
    if (message.messageId == null || message.messageId!.isEmpty) {
      return;
    }         
    
    if (messageIdOld == message.messageId) {
      debugPrint('messageIdOld == messageId  return');
      return;
    }
    messageIdOld = message.messageId;
  }}

@cmorsucci
Copy link

Yes, I also solved it as per the suggestion: #13366 (comment)

@niosme
Copy link

niosme commented Oct 30, 2024

Also messages without title and body ( silent notifications ) never received at ios 18. And those with title and body fired twice.

@vanyasem
Copy link

vanyasem commented Oct 30, 2024

@niosme data-only notifications work for me on iOS 18 with the following configuration:

"content-available": 1,
"mutable-content": 1,
"alert": "",
"sound": "default"

Adding the sound key makes them arrive for me
But if set to default, notifications wouldn't be silent, as they would trigger the default notification sound. Luckily, you can bundle your own sound in the application, including a completely silent sound file :P

Here is a 1-second silent audio file in the correct format. Just drag and drop it into your project in Xcode and add to the target when prompted: silent.caf.zip. Then set the "sound": "silent.caf" on your backend

Snippet from Apple APN Payload Key Reference:

The value of this key is the name of a sound file in your app’s main bundle or in the Library/Sounds folder of your app’s data container. If the sound file cannot be found, or if you specify defaultfor the value, the system plays the default alert sound.

For details about providing sound files for notifications; see Preparing Custom Alert Sounds.

Also see https://stackoverflow.com/questions/19239737/silent-push-notification-in-ios-7-does-not-work/

@niosme
Copy link

niosme commented Oct 30, 2024

@niosme data-only notifications work for me on iOS 18 with the following configuration:

"content-available": 1,
"mutable-content": 1,
"alert": "",
"sound": "default"

Adding "sound": "default" makes them not-so-silent, but at least they arrive You can use any string instead of default, the contents don't matter

See https://stackoverflow.com/questions/19239737/silent-push-notification-in-ios-7-does-not-work/

I just tryed that and doesnt work. I use this code in php to send a notification and it was working fine before the update.
The code i use in php is the following. If i set the silent to false it works as expected and the listen event is triggered fine. if is set isSilent to true which was working on previous versions nothing is triggered on the flutter app but setting to isSilent to false triggers the listen event twice ( which i fixed that with the above suggestions ).

use \Kreait\Firebase\Factory as FirebaseFactory;
use \Kreait\Firebase\Messaging\CloudMessage as FirebaseCloudMessage;
use \Kreait\Firebase\Exception\MessagingException as FirebaseMessagingException;

/**
 * helper.
 *
 * @since  1.0.0
 */
class FirebaseHelper
{

    private $messaging;
    private $isFirebaseInitialized = false;
    private $errorMessage = '';

     /**
     * Constructor. Initializes the Firebase messaging service.
     *
     * Requires the `kreait/firebase-php` library installed via composer.
     * Expects a `firebase_config.json` file in the component's administrator assets folder.
     *
     * @return void
     */
    function __construct() {
       
        require_once JPATH_ROOT.'/administrator/components/com_myapp/assets/firebase/firebase_library/vendor/autoload.php';// Include the Firebase PHP library
       
        $firebase_config_path = JPATH_ROOT.'/administrator/components/com_myapp/assets/firebase/firebase_config.json';

        if (!file_exists($firebase_config_path)) { $this->errorMessage = "Firebase configuration file not found."; return; }

        $firebase_config = json_decode(file_get_contents($firebase_config_path), true);
        $firebase = (new FirebaseFactory)->withServiceAccount($firebase_config);
        $this->messaging = $firebase->createMessaging();
        $this->isFirebaseInitialized = true;
    }

    /**
     * Sends a notification to a user or all devices.
     *
     * @param   int         $userId       The user ID. Set to 0 to send to all devices.
     * @param   string      $title        The notification title.
     * @param   string      $body         The notification body.
     * @param   array       $data         Optional data payload.
     * @param   bool        $allDevices   Send to all devices (including inactive) if true, otherwise only active devices.
     * @param   string|null $deviceType   Optional device type filter (ios, android, web).
     * @param   array       $actions      Array of actions for call-style notification (e.g., ['accept', 'reject']).
     *
     *
     * @return array An array containing 'error' (boolean) and 'message' (string) indicating success or failure.
     */
    public function sendNotification($userId, $title , $body , $data = [], $allDevices = false, $deviceType = null, $actions = [], $isSilent = false){
        $response = [
            'error' => false,
            'message' => '',
	        'messages' => []
        ];

		$errorOccured = false;

        // Check if firebase is initiallized succesfully
        if (!$this->isFirebaseInitialized) {
            $response['message'] = $this->errorMessage;
            error_log($response['message']);
            return $response;
        }

        // Get the user registration token based on the user id
        $db = Factory::getContainer()->get('DatabaseDriver');;
        $query = $db->getQuery(true);
        $query->select('fcm_token');
        $query->from('#__firebase_notifications');

        if ($userId>0)      $query->where('user_id = ' . (int) $userId);
        if (!$allDevices)   $query->where('is_active = 1'); // Send to all active devices
        if ($deviceType)    $query->where('device_type = ' . $db->quote($deviceType));

        $db->setQuery($query);
        $registrationTokens = $db->loadColumn();

        if (empty($registrationTokens)) {
            $response['message'] = 'No registration tokens found for user ID: ' . $userId;
            error_log($response['message']);
            return $response;
        }

        // Continue to send the notification
       if (!$isSilent) {
            $notification = [
                'title' => $title,
                'body' => $body,
            ];
        };



            foreach ($registrationTokens as $registrationToken) {

	            try {
	                // Create the message
	                $message = FirebaseCloudMessage::withTarget('token', $registrationToken)
	                    ->withData($data);

	                if (!$isSilent) {
	                    $message= $message->withNotification($notification);
	                }


	                // Add actions if provided
	                if (!empty($actions)) {
	//                    $message = $message->withData(['actions' => $actions]);

						$message = $message->withData(array_merge($data, ['actions' => json_encode($actions)]));

	                    // Android-specific configuration
	                    $message = $message->withAndroidConfig([
	                        'priority' => 'high',
	                        // 'click_action' => 'CALL_CATEGORY',
	                    ]);

	                    // iOS-specific configuration
	                    $message = $message->withApnsConfig([
	                        'mutable_content' => 1,
		                    'content_available' => 1,
		                    'alert' => '',
		                    'sound' => 'default',
		                    'priority' => 'high',
	                    ]);
	                }

	                $firebase_response = $this->messaging->send($message); // Send the message

	                if (isset($firebase_response['failure'])) {
		                $errorOccured = true;
						$response['messages'][] ='Error sending notification to token ' . $registrationToken . ': ' . $firebase_response['failure'];
	                }else{
		                $response['messages'][] = 'Notification to token ' . $registrationToken . ' sended successfully';
	                }
	            } catch (FirebaseMessagingException $e) {
		            $errorOccured = true;
		            if (strpos($e->getMessage(), 'Requested entity was not found') !== false) {
			            $response['messages'][] = 'Error sending notification to token ' . $registrationToken . '(invalid token) : ' . $e->getMessage() . " deleting token...";
			            // Remove invalid token from database
			            $this->removeInvalidToken($registrationToken);
		            } else {
			            // Handle other FirebaseMessagingExceptions differently
			            $response['messages'][] = 'Temporary error sending notification to token ' . $registrationToken . ': ' . $e->getMessage();
			            // You might log the error or retry later
		            }
	            }

            }

            if (!$errorOccured) {// All messages sent successfully
                $response['message'] = 'Notification sent successfully to '.(!$allDevices?'the active devices':'all devices').'!';
            } else {
	            $response['error'] = true;
                $response['message'] = 'Some notifications failed to send';
            }

        if($response['error']){
            error_log($response['message']);
        }

        return $response;
    }

}

@vanyasem
Copy link

@niosme

	                    // iOS-specific configuration
	                    $message = $message->withApnsConfig([
	                        'mutable_content' => 1,
		                    'content_available' => 1,
		                    'alert' => '',
		                    'sound' => 'default',
		                    'priority' => 'high',
	                    ]);

I'm pretty sure that the correct keys are mutable-content and content-available - with a dash instead of an underscore: https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification

I'd also suggest to try to remove priority: high

@niosme
Copy link

niosme commented Oct 30, 2024

@niosme

	                    // iOS-specific configuration
	                    $message = $message->withApnsConfig([
	                        'mutable_content' => 1,
		                    'content_available' => 1,
		                    'alert' => '',
		                    'sound' => 'default',
		                    'priority' => 'high',
	                    ]);

I'm pretty sure that the correct keys are mutable-content and content-available - with a dash instead of an underscore: https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification

I'd also suggest to try to remove priority: high

You re right. i followed also this https://firebase-php.readthedocs.io/en/7.15.0/cloud-messaging.html because i saw i was passing the config parameters the wrong way.
By setting the alert to '' it works fine and doesnt trigger the alert. The frontend works as expected. Now i am checking the background listener FirebaseMessaging.onBackgroundMessage which it looks like its not triggered on silent notifications. Any idea on that?

@vanyasem
Copy link

@niosme setting the sound property fixed the issue for me, as I mentioned in my original comment above: #13366 (comment)

@cmorsucci
Copy link

Could someone provide a complete json of what you send? Maybe I can catch my mistake

@niosme
Copy link

niosme commented Oct 30, 2024

@niosme setting the sound property fixed the issue for me, as I mentioned in my original comment above: #13366 (comment)

it works fine. But the background message listener is not triggering. Only the frontend listener works as expected.

@cmorsucci
Copy link

@niosme setting the sound property fixed the issue for me, as I mentioned in my original comment above: #13366 (comment)

it works fine. But the background message listener is not triggering. Only the frontend listener works as expected.

Yes, in fact, as you suggest, that background doesn't work for me either :S

@niosme
Copy link

niosme commented Oct 30, 2024

@niosme setting the sound property fixed the issue for me, as I mentioned in my original comment above: #13366 (comment)

it works fine. But the background message listener is not triggering. Only the frontend listener works as expected.

Yes, in fact, as you suggest, that background doesn't work for me either :S

Maybe we can find a workaround here.
#13476

@niosme
Copy link

niosme commented Oct 30, 2024

@niosme setting the sound property fixed the issue for me, as I mentioned in my original comment above: #13366 (comment)

it works fine. But the background message listener is not triggering. Only the frontend listener works as expected.

Yes, in fact, as you suggest, that background doesn't work for me either :S

Made it work like this

AppDelegate.swift ( just copy paste this code and keep the previous if the bug is fixed in a future version )


import Firebase
import Flutter
import UIKit
import flutter_local_notifications

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FirebaseApp.configure()

    // Start LocalNotifications
    // This is required to make any communication available in the action isolate.
    FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
      GeneratedPluginRegistrant.register(with: registry)
    }

    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }
    // End LocalNotifications

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

  override func application(
    _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
  ) {
    super.application(
      application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler
    )
  }

}

and also at ios directory info.plist

	<key>FirebaseAppDelegateProxyEnabled</key>
	<true/>

in main.dart inside initState put those ( Just realized that tha main.dart code is not needed )

    const MethodChannel _platform =
    MethodChannel('com.app.my');//here the id of the app
    _platform.setMethodCallHandler((MethodCall call) async {
      if (call.method == "handleMessageBackground") {
        final RemoteMessage message = RemoteMessage(
            notification: RemoteNotification(
                title: call.arguments["aps"]["alert"]["title"],
                body: call.arguments["aps"]["alert"]["body"]),
            data: Map<String, dynamic>.from(call.arguments));
        //whatever you want to do but this also triggers it
      }
    });

@russellwheatley
Copy link
Member

@justChris - I have a fix/workaround on this branch if you want to test it out: #13572

Would be helpful if anyone else can confirm as well, please 🙏

@russellwheatley russellwheatley added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Oct 30, 2024
@russellwheatley
Copy link
Member

Note - I tested on iOS 18.1 and it seems it was fixed without any intervention on FlutterFire.

@vanyasem
Copy link

vanyasem commented Oct 30, 2024

@niosme

Maybe we can find a workaround here.
#13476

oh yeah you're right, I totally forgot about that
that's a separate issue, it's been fixed in master but not yet released to stable

To fix, replace firebase_messaging in pubspec.yaml with this:

# https://github.com/firebase/flutterfire/pull/13525
# TODO: Switch to upstream when it's released to pub.dev
firebase_messaging:
  git:
    url: https://github.com/firebase/flutterfire.git
    path: packages/firebase_messaging/firebase_messaging
    ref: 8ff0f88

I do not suggest editing AppDelegate.swift, as it's a hack and not a correct/permanent solution.
You better temporarily switch to the git dependency, via a commit reference as seen above.

@avinashk369

This comment was marked as off-topic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blocked: customer-response Waiting for customer response, e.g. more information was requested. platform: ios Issues / PRs which are specifically for iOS. plugin: messaging type: bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.