flutterfire icon indicating copy to clipboard operation
flutterfire copied to clipboard

πŸ› [firebase_messaging] APNS token has not been set yet. Please ensure the APNS token is available by calling getAPNSToken()

Open praveengitsit-pro opened this issue 2 years ago β€’ 14 comments

Bug report

I am trying to implement Push Notifications in my Flutter app. But I get the following error:

APNS token has not been set yet. Please ensure the APNS token is available by calling getAPNSToken().

Some of the steps I have done using the flutterfire_cli. But since I am using flavors, I also had to do some steps on my own, like having the configurations (different GoogleService-Info.plist for each flavor corresponding to the a different Firebase project) for different flavors inside a ios/config directory and using a script to copy these resources during build time.

Steps to reproduce

Steps to reproduce the behavior:

  1. Create a Flutter project using flutter version 3.13.2
  2. Integrate firebase_messaging: ^14.7.10 and firebase_core: ^2.24.2
  3. Implement flavors for different environments, including the script used to copy the required resources to the correct directory (I can provide this later on, if needed as well)
  4. Use the flutterfire_cli to generate initialization data for each flavor
  5. Connect to an iOS device (I am using a real device, iPhone X with iOS 16.1.1)

Expected behavior

I would want Push notifications feature to work correctly in my iOS device


Additional context

The getAPNSToken() function always returns null in my case. I have checked multiple times the configurations within XCode for the bundle IDs to be correct and corresponding to their respective Firebase projects as well. The app runs exactly as intended in Android, and this issue is only for iOS devices.

I am using APNS Key instead of the APNS certificates for the projects. I mention this explicitly here because the docs have a title for the key but the content for the certificate (See: https://firebase.google.com/docs/cloud-messaging/flutter/client#upload_your_apns_authentication_key )

In Info.plist, I get the error, no matter if I set the FirebaseAppDelegateProxyEnabled to true or false. Along with that, I also get the error whether or not I do the following in my AppDelegate.swift

import Firebase

Firebase.configure()

Some answers in S/O & Github mention importing Firebase along with the code for configurations, and some only import the Firebase module. I have noticed that the code for configuration results in the app building and crashing immediately on startup, so I am a bit lost here as well.

I cannot solely rely on the CLI to do the work for me, as schemes/flavors are not yet fully supported by the CLI. (See issue: https://github.com/invertase/flutterfire_cli/issues/14 )

Possible resolve:

Also, related to https://github.com/firebase/flutterfire/issues/12070. The author of that issue has resolved it by downgrading their dependencies to a lower version, but I am not sure if that is the best way forward. If nothing else works, I will be using this as a last option, though.


Flutter doctor

Click To Expand
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ A new version of Flutter is available!                  β”‚
β”‚                                                         β”‚
β”‚ To update to the latest version, run "flutter upgrade". β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Doctor summary (to see all details, run flutter doctor -v):
[βœ“] Flutter (Channel stable, 3.13.2, on macOS 14.3 23D56 darwin-arm64, locale en-NP)
[βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[βœ“] Xcode - develop for iOS and macOS (Xcode 15.2)
[βœ—] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[βœ“] Android Studio (version 2021.3)
[βœ“] VS Code (version 1.86.0-insider)
[βœ“] Connected device (2 available)
    ! Error: Praveen Bhusal’s iPhone is not available because it is unpaired. Pair with the device in the Xcode Devices Window, and respond to any pairing prompts on the device. (code -29)
[βœ“] Network resources

! Doctor found issues in 1 category.


Flutter dependencies

Click To Expand
Dart SDK 3.1.0
Flutter SDK 3.13.2
[project_name_and_version_redacted]

dependencies:
- android_path_provider 0.3.0 [flutter]
- auto_size_text 3.0.0 [flutter]
- collection 1.17.2
- connectivity_plus 5.0.2 [flutter flutter_web_plugins connectivity_plus_platform_interface js meta nm]
- cupertino_icons 1.0.6
- dartz 0.10.1
- device_info_plus 4.1.3 [flutter device_info_plus_platform_interface device_info_plus_macos device_info_plus_linux device_info_plus_web device_info_plus_windows]
- equatable 2.0.5 [collection meta]
- firebase_core 2.24.2 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_messaging 14.7.10 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- fl_chart 0.62.0 [equatable flutter]
- floor 1.4.2 [collection floor_annotation flutter meta path sqflite sqflite_common_ffi sqlparser]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math web sky_engine]
- flutter_bloc 8.1.3 [bloc flutter provider]
- flutter_downloader 1.11.1 [flutter]
- flutter_keyboard_visibility 5.4.1 [meta flutter_keyboard_visibility_platform_interface flutter_keyboard_visibility_linux flutter_keyboard_visibility_macos flutter_keyboard_visibility_web flutter_keyboard_visibility_windows flutter]
- flutter_local_notifications 16.3.0 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math web]
- flutter_svg 1.1.6 [flutter meta path_drawing vector_math xml]
- fluttertoast 8.2.2 [flutter flutter_web_plugins]
- formz 0.4.1
- geocoding 2.1.0 [flutter geocoding_platform_interface geocoding_android geocoding_ios]
- geolocator 10.0.0 [flutter geolocator_platform_interface geolocator_android geolocator_apple geolocator_web geolocator_windows]
- http 0.13.6 [async http_parser meta]
- http_interceptor 1.0.2 [http]
- intl 0.18.1 [clock meta path]
- intl_phone_field 3.2.0 [flutter]
- json_serializable 6.7.1 [analyzer async build build_config collection json_annotation meta path pub_semver pubspec_parse source_gen source_helper]
- material_design_icons_flutter 7.0.7296 [flutter]
- multi_select_flutter 4.1.3 [flutter collection]
- open_filex 4.3.2 [flutter ffi]
- package_info_plus 3.1.2 [ffi flutter flutter_web_plugins http meta path package_info_plus_platform_interface win32]
- path_provider 2.1.1 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows]
- pdfx 2.3.0 [flutter flutter_web_plugins plugin_platform_interface js device_info_plus uuid meta extension synchronized universal_platform photo_view vector_math]
- pendo_sdk 2.22.0 [flutter]
- permission_handler 10.4.3 [flutter meta permission_handler_android permission_handler_apple permission_handler_windows permission_handler_platform_interface]
- proshore_localization 0.0.1 [flutter]
- rxdart 0.27.7
- shared_preferences 2.2.1 [flutter shared_preferences_android shared_preferences_foundation shared_preferences_linux shared_preferences_platform_interface shared_preferences_web shared_preferences_windows]
- stream_transform 2.1.0
- table_calendar 3.0.9 [flutter intl simple_gesture_detector]
- url_launcher 6.1.14 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- very_good_analysis 3.1.0
- webview_flutter 4.2.4 [flutter webview_flutter_android webview_flutter_platform_interface webview_flutter_wkwebview]

dev dependencies:
- dart_style 2.3.2 [analyzer args path pub_semver source_span]
- floor_generator 1.4.2 [analyzer build build_config code_builder collection floor_annotation meta source_gen strings]
- flutter_lints 2.0.3 [lints]
- flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math async boolean_selector characters collection material_color_utilities meta source_span stream_channel string_scanner term_glyph web]

transitive dependencies:
- _fe_analyzer_shared 61.0.0 [meta]
- _flutterfire_internals 1.3.16 [collection firebase_core firebase_core_platform_interface flutter meta]
- analyzer 5.13.0 [_fe_analyzer_shared collection convert crypto glob meta package_config path pub_semver source_span watcher yaml]
- args 2.4.2
- async 2.11.0 [collection meta]
- bloc 8.1.2 [meta]
- 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]
- built_collection 5.1.1
- built_value 8.6.2 [built_collection collection fixnum meta]
- characters 1.3.0
- charcode 1.3.1
- checked_yaml 2.0.3 [json_annotation source_span yaml]
- clock 1.1.1
- code_builder 4.6.0 [built_collection built_value collection matcher meta]
- connectivity_plus_platform_interface 1.2.4 [flutter meta plugin_platform_interface]
- convert 3.1.1 [typed_data]
- crypto 3.0.3 [typed_data]
- dbus 0.7.8 [args ffi meta xml]
- device_info_plus_linux 3.0.0 [device_info_plus_platform_interface file flutter meta]
- device_info_plus_macos 3.0.0 [device_info_plus_platform_interface flutter]
- device_info_plus_platform_interface 3.0.0 [flutter meta plugin_platform_interface]
- device_info_plus_web 3.0.0 [device_info_plus_platform_interface flutter_web_plugins flutter]
- device_info_plus_windows 4.1.0 [device_info_plus_platform_interface ffi flutter win32]
- extension 0.5.0
- fake_async 1.3.1 [clock collection]
- ffi 2.1.0
- file 6.1.4 [meta path]
- firebase_core_platform_interface 5.0.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.10.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_messaging_platform_interface 4.5.18 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.5.18 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- fixnum 1.1.0
- floor_annotation 1.4.2 [meta]
- flutter_keyboard_visibility_linux 1.0.0 [flutter_keyboard_visibility_platform_interface flutter]
- flutter_keyboard_visibility_macos 1.0.0 [flutter_keyboard_visibility_platform_interface flutter]
- flutter_keyboard_visibility_platform_interface 2.0.0 [flutter meta plugin_platform_interface]
- flutter_keyboard_visibility_web 2.0.0 [flutter_keyboard_visibility_platform_interface flutter_web_plugins flutter]
- flutter_keyboard_visibility_windows 1.0.0 [flutter_keyboard_visibility_platform_interface flutter]
- flutter_local_notifications_linux 4.0.0+1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories]
- flutter_local_notifications_platform_interface 7.0.0+1 [flutter plugin_platform_interface]
- flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math web]
- geocoding_android 2.1.2 [flutter geocoding_platform_interface]
- geocoding_ios 2.1.0 [flutter geocoding_platform_interface]
- geocoding_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- geolocator_android 4.2.2 [flutter geolocator_platform_interface uuid]
- geolocator_apple 2.2.7 [flutter geolocator_platform_interface]
- geolocator_platform_interface 4.0.8 [flutter plugin_platform_interface vector_math meta]
- geolocator_web 2.1.6 [flutter flutter_web_plugins geolocator_platform_interface]
- geolocator_windows 0.2.0 [flutter geolocator_platform_interface]
- glob 2.1.2 [async collection file path string_scanner]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- js 0.6.7 [meta]
- json_annotation 4.8.1 [meta]
- lints 2.1.1
- lists 1.0.1 [meta]
- logging 1.2.0
- matcher 0.12.16 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.5.0 [collection]
- meta 1.9.1
- nested 1.0.0 [flutter]
- nm 0.5.0 [dbus]
- package_config 2.1.0 [path]
- package_info_plus_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- path 1.8.3
- path_drawing 1.0.1 [vector_math meta path_parsing flutter]
- path_parsing 1.0.1 [vector_math meta]
- path_provider_android 2.2.0 [flutter path_provider_platform_interface]
- path_provider_foundation 2.3.1 [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.1 [flutter platform plugin_platform_interface]
- path_provider_windows 2.2.1 [ffi flutter path path_provider_platform_interface win32]
- permission_handler_android 10.3.4 [flutter permission_handler_platform_interface]
- permission_handler_apple 9.1.4 [flutter permission_handler_platform_interface]
- permission_handler_platform_interface 3.11.3 [flutter meta plugin_platform_interface]
- permission_handler_windows 0.1.3 [flutter permission_handler_platform_interface]
- petitparser 5.4.0 [meta]
- photo_view 0.14.0 [flutter]
- platform 3.1.2
- plugin_platform_interface 2.1.6 [meta]
- provider 6.0.5 [collection flutter nested]
- pub_semver 2.1.4 [collection meta]
- pubspec_parse 1.2.3 [checked_yaml collection json_annotation pub_semver yaml]
- shared_preferences_android 2.2.1 [flutter shared_preferences_platform_interface]
- shared_preferences_foundation 2.3.4 [flutter shared_preferences_platform_interface]
- shared_preferences_linux 2.3.1 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface]
- shared_preferences_platform_interface 2.3.1 [flutter plugin_platform_interface]
- shared_preferences_web 2.2.1 [flutter flutter_web_plugins shared_preferences_platform_interface]
- shared_preferences_windows 2.3.1 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface]
- simple_gesture_detector 0.2.0 [flutter]
- sky_engine 0.0.99
- source_gen 1.4.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]
- sqflite 2.3.0 [flutter sqflite_common path]
- sqflite_common 2.5.0 [synchronized path meta]
- sqflite_common_ffi 2.3.0+2 [sqlite3 sqflite_common synchronized path meta]
- sqlite3 2.1.0 [collection ffi js meta path]
- sqlparser 0.27.0 [meta collection source_span charcode]
- stack_trace 1.11.0 [path]
- stream_channel 2.1.1 [async]
- string_scanner 1.2.0 [source_span]
- strings 0.2.2 [characters unicode]
- synchronized 3.1.0
- term_glyph 1.2.1
- test_api 0.6.0 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph]
- timezone 0.9.2 [path]
- typed_data 1.3.2 [collection]
- unicode 0.3.1 [lists]
- universal_platform 1.0.0+1
- url_launcher_android 6.1.0 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.1.5 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.0.6 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.0.7 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.1.5 [flutter plugin_platform_interface]
- url_launcher_web 2.0.19 [flutter flutter_web_plugins url_launcher_platform_interface]
- url_launcher_windows 3.0.8 [flutter url_launcher_platform_interface]
- uuid 3.0.7 [crypto]
- vector_math 2.1.4
- watcher 1.1.0 [async path]
- web 0.1.4-beta
- webview_flutter_android 3.9.5 [flutter webview_flutter_platform_interface]
- webview_flutter_platform_interface 2.5.1 [flutter meta plugin_platform_interface]
- webview_flutter_wkwebview 3.7.4 [flutter path webview_flutter_platform_interface]
- win32 3.1.4 [ffi]
- xdg_directories 1.0.3 [meta path]
- xml 6.3.0 [collection meta petitparser]
- yaml 3.1.2 [collection source_span string_scanner]


Would be happy to provide any more info to resolve the issue, if needed.

praveengitsit-pro avatar Feb 01 '24 07:02 praveengitsit-pro

Thanks for the report @praveengitsit-pro Check this and see if it helps to resolve your case or not.

darshankawar avatar Feb 01 '24 11:02 darshankawar

@darshankawar The said solution does not work for me. I have added a delay of 5 seconds initially before calling getAPNSToken(). In fact, I cannot get the APNS token even if I call the method again some time later.

I am a little confused about having to call this method before doing anything else with FCM. Does this mean that if it runs into this error once, any subsequent calls to this method will not work? Or does this mean that you can delay the method call and it will work eventually?

I also think having to add a delay is not a sustainable solution. This should ultimately be fixed in the package we are using. And in the meantime, an acceptable delay time (like: 2s, 5s, etc) has to clarified in some documentation, too

praveengitsit-pro avatar Feb 02 '24 07:02 praveengitsit-pro

I am able to Receive APNS tokes, but not message from FCM Console. From CloudKit just works with APNS, but from FCM with token, not.

using 10.20.0 pods

flakerimi avatar Feb 05 '24 02:02 flakerimi

I upgraded my Flutter project to v3.16.9, and the error is still there. Since, the upgrade did not work, I think there might be something wrong with something else entirely

iOS directory structure

Inside each directory is a file named GoogleService-Info.plist for the respective Firebase projects of each of the flavors.

Screenshot_2024-02-06_at_15_07_20


Custom script for copying GoogleService-Info.plist

PS. I am using zsh

setopt KSH_ARRAYS BASH_REMATCH
environment="default"

# Regex to extract the scheme name from the Build Configuration
# We have named our Build Configurations as Debug-dev, Debug-prod etc.
# Here, dev and prod are the scheme names. This kind of naming is required by Flutter for flavors to work.
# We are using the $CONFIGURATION variable available in the XCode build environment to extract 
# the environment (or flavor)
# For eg.
# If CONFIGURATION="Debug-prod", then environment will get set to "prod".
if [[ $CONFIGURATION =~ -([^-]*)$ ]]; then
environment=${BASH_REMATCH[1]}
fi

echo $environment

# Name and path of the resource we're copying
GOOGLESERVICE_INFO_PLIST=GoogleService-Info.plist
GOOGLESERVICE_INFO_FILE=${PROJECT_DIR}/config/${environment}/${GOOGLESERVICE_INFO_PLIST}

# Make sure GoogleService-Info.plist exists
echo "Looking for ${GOOGLESERVICE_INFO_PLIST} in ${GOOGLESERVICE_INFO_FILE}"
if [ ! -f $GOOGLESERVICE_INFO_FILE ]
then
echo "No GoogleService-Info.plist found. Please ensure it's in the proper directory."
exit 1
fi

# Get a reference to the destination location for the GoogleService-Info.plist
# This is the default location where Firebase init code expects to find GoogleServices-Info.plist file
PLIST_DESTINATION=${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app
echo "Will copy ${GOOGLESERVICE_INFO_PLIST} to final destination: ${PLIST_DESTINATION}"

# Copy over the prod GoogleService-Info.plist for Release builds
cp "${GOOGLESERVICE_INFO_FILE}" "${PLIST_DESTINATION}"
unsetopt KSH_ARRAYS


Under Build Phases in XCode, the above script falls in: Screenshot 2024-02-06 at 15 14 56

Flutter doctor

Click To Expand

  ╔════════════════════════════════════════════════════════════════════════════╗
  β•‘                 Welcome to Flutter! - https://flutter.dev                  β•‘
  β•‘                                                                            β•‘
  β•‘ The Flutter tool uses Google Analytics to anonymously report feature usage β•‘
  β•‘ statistics and basic crash reports. This data is used to help improve      β•‘
  β•‘ Flutter tools over time.                                                   β•‘
  β•‘                                                                            β•‘
  β•‘ Flutter tool analytics are not sent on the very first run. To disable      β•‘
  β•‘ reporting, type 'flutter config --no-analytics'. To display the current    β•‘
  β•‘ setting, type 'flutter config'. If you opt out of analytics, an opt-out    β•‘
  β•‘ event will be sent, and then no further information will be sent by the    β•‘
  β•‘ Flutter tool.                                                              β•‘
  β•‘                                                                            β•‘
  β•‘ By downloading the Flutter SDK, you agree to the Google Terms of Service.  β•‘
  β•‘ The Google Privacy Policy describes how data is handled in this service.   β•‘
  β•‘                                                                            β•‘
  β•‘ Moreover, Flutter includes the Dart SDK, which may send usage metrics and  β•‘
  β•‘ crash reports to Google.                                                   β•‘
  β•‘                                                                            β•‘
  β•‘ Read about data we send with crash reports:                                β•‘
  β•‘ https://flutter.dev/docs/reference/crash-reporting                         β•‘
  β•‘                                                                            β•‘
  β•‘ See Google's privacy policy:                                               β•‘
  β•‘ https://policies.google.com/privacy                                        β•‘
  β•‘                                                                            β•‘
  β•‘ To disable animations in this tool, use 'flutter config --no-animations'.  β•‘
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Downloading Material fonts...                                      375ms
Downloading Gradle Wrapper...                                       26ms
Downloading package sky_engine...                                   76ms
Downloading flutter_patched_sdk tools...                           198ms
Downloading flutter_patched_sdk_product tools...                   206ms
Downloading darwin-arm64 tools...                                   4.3s
Downloading libimobiledevice...                                     34ms
Downloading usbmuxd...                                              24ms
Downloading libplist...                                             23ms
Downloading openssl...                                              83ms
Downloading ios-deploy...                                           29ms
Downloading darwin-arm64/font-subset tools...                       4.4s
Doctor summary (to see all details, run flutter doctor -v):
[βœ“] Flutter (Channel stable, 3.16.9, on macOS 14.3 23D56 darwin-arm64, locale en-NP)
[βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[βœ“] Xcode - develop for iOS and macOS (Xcode 15.2)
[βœ—] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[βœ“] Android Studio (version 2021.3)
[βœ“] VS Code (version 1.86.0-insider)
[βœ“] Connected device (2 available)
[βœ“] Network resources

! Doctor found issues in 1 category.

praveengitsit-pro avatar Feb 06 '24 09:02 praveengitsit-pro

Update: Downgrading firebase dependencies still resulting in the same error

I even tried to use the solution proposed in this comment under a similar issue, and that option does not work either.

The said solution did land me in some other zone, where I found something I had previously missed to add in my Info.plist from the currently archived guide. Here, the issue was found to be:

flutter [FirebaseAnalytics][I-ACS023129] Network fetch failed. Will retry later. Code, error: 0, Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server."

I added the necessary config but it resulted in the same of fetching APNS token as well as the network fail issue mentioned above. I also tried with the above key added to the plist with my previous configuration and there has been no progress there either.

praveengitsit-pro avatar Feb 06 '24 11:02 praveengitsit-pro

Thanks for the details @praveengitsit-pro I am wondering if this occuring due to flavors you are using in the app. Is there a way for you to check if without flavors, do you still get same behavior or not ?

darshankawar avatar Feb 06 '24 12:02 darshankawar

I have the same problem.

A few month ago I had the same issue, I had to downgrade to

  firebase_core: 2.7.1
  firebase_messaging: 14.2.6
  firebase_core_platform_interface: 4.5.3

And then with

  firebase_core: ^2.15.1
  firebase_messaging: ^14.6.7

It was fixed.

And the problem is back. I'm not sure which version is the problem now.

EDIT:

I tried to downgrade back to

  firebase_core: 2.15.1
  firebase_messaging: 14.6.7
  firebase_core_platform_interface: 4.8.0

I found these versions - with which I didn't get the error message - in pubspec.lock. And strangely enough, the error is present.

So I tried to downgrade even more, to the versions I had locked until the bug was fixed...

  firebase_core: 2.7.1
  firebase_messaging: 14.2.6
  firebase_core_platform_interface: 4.5.3

And it fixes the problem.

Here are some issues from when the bug appeared, if that helps... https://github.com/firebase/flutterfire/issues/10656 https://github.com/firebase/firebase-ios-sdk/issues/11459

smbpunt avatar Feb 06 '24 14:02 smbpunt

@darshankawar

Yes, I can still reproduce the issue by creating a separate Flutter project and setting up Firebase entirely from the flutterfire_cli.


Firebase service class

Click To Expand
import 'dart:developer';
import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';

class FirebaseNotificationsService {
  FirebaseNotificationsService();

  /// Create an instance of Firebase Messaging
  final FirebaseMessaging _fcm = FirebaseMessaging.instance;

  /// Function to initialize notifications
  Future<void> initialize() async {
    /// Request permission to receive notifications
    NotificationSettings settings = await _fcm.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    /// If permission granted, listen to messages
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      await getNotificationToken();
    }
  }

  Future<String?> getNotificationToken() async {
    if (Platform.isIOS) {
      Future.delayed(const Duration(seconds: 5), () async {
        final apnsToken = await _fcm.getAPNSToken();
        log("apnsToken: $apnsToken");
        final fcmToken = await _fcm.getToken();
        log("fcmToken: $fcmToken");
        return fcmToken;
      });
    } else {
      final fcmToken = await _fcm.getToken();
      log("fcmToken: $fcmToken");
      return fcmToken;
    }
  }
}

main.dart

Click To Expand
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:issue_with_fcm_apns_token/firebase_options.dart';

import 'firebase_notification_service.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  final notificationService = FirebaseNotificationsService();
  notificationService.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Logs

Click To Expand
Warning: Unable to create restoration in progress marker file
10.18.0 - [FirebaseCore][I-COR000005] No app has been configured yet.
10.18.0 - [FirebaseMessaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging
to ensure proper integration.
fopen failed for data file: errno = 2 (No such file or directory)
Errors found! Invalidating cache...
Debug service listening on ws://127.0.0.1:53796/BnrXn_brSt4=/ws
Syncing files to device Phone...
[log] apnsToken: null
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_messaging/apns-token-not-set] APNS token has not been set yet. Please ensure the APNS token is available by calling `getAPNSToken()`.
#0      MethodChannelFirebaseMessaging._APNSTokenCheck (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:138:9)
<asynchronous suspension>
#1      MethodChannelFirebaseMessaging.getToken (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:244:5)
<asynchronous suspension>
#2      FirebaseNotificationsService.getNotificationToken.<anonymous closure> (package:issue_with_fcm_apns_token/firebase_notification_service.dart:69:26)
<asynchronous suspension>

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, 3.13.2, on macOS 14.3 23D56 darwin-arm64, locale en-NP)
[βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[βœ“] Xcode - develop for iOS and macOS (Xcode 15.2)
[βœ—] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[βœ“] Android Studio (version 2021.3)
[βœ“] VS Code (version 1.87.0-insider)
[βœ“] Connected device (2 available)
[βœ“] Network resources

! Doctor found issues in 1 category.


Flutter dependencies

Click To Expand
Dart SDK 3.1.0
Flutter SDK 3.13.2
issue_with_fcm_apns_token 1.0.0+1

dependencies:
- firebase_core 2.24.2 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_messaging 14.7.10 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math web sky_engine]

dev dependencies:
- flutter_lints 2.0.3 [lints]
- flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math async boolean_selector characters collection material_color_utilities meta source_span stream_channel string_scanner term_glyph web]

transitive dependencies:
- _flutterfire_internals 1.3.16 [collection firebase_core firebase_core_platform_interface flutter meta]
- async 2.11.0 [collection meta]
- boolean_selector 2.1.1 [source_span string_scanner]
- characters 1.3.0
- clock 1.1.1
- collection 1.17.2
- fake_async 1.3.1 [clock collection]
- firebase_core_platform_interface 5.0.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.10.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_messaging_platform_interface 4.5.18 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.5.18 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math web]
- js 0.6.7 [meta]
- lints 2.1.1
- matcher 0.12.16 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.5.0 [collection]
- meta 1.9.1
- path 1.8.3
- plugin_platform_interface 2.1.8 [meta]
- sky_engine 0.0.99
- source_span 1.10.0 [collection path term_glyph]
- stack_trace 1.11.0 [path]
- stream_channel 2.1.1 [async]
- string_scanner 1.2.0 [source_span]
- term_glyph 1.2.1
- test_api 0.6.0 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph]
- vector_math 2.1.4
- web 0.1.4-beta

praveengitsit-pro avatar Feb 06 '24 17:02 praveengitsit-pro

Update: Not working with a similar issue on another project

Tried with another project where notifications was previously working on the same physical device. And now, it is no longer working. So far as I can recall, the only thing that is different during when the notifications was previously working and now is that I have upgraded my development machine's version (to Mac 14.3) along with XCode and Command line tools. It is likely that the phone's OS was also upgraded but this I can't say with certainty.


Logs

Click to expand ``` (lldb) 2024-02-06 23:40:52.654682+0545 Runner[22693:2353942] [VERBOSE-2:FlutterDarwinContextMetalImpeller.mm(35)] Using the Impeller rendering backend. fopen failed for data file: errno = 2 (No such file or directory) Errors found! Invalidating cache... Debug service listening on ws://127.0.0.1:57765/nBS3-MYIylg=/ws Syncing files to device Phone... FLTFirebaseMessaging: An error occurred while calling method Messaging#getToken, errorOrNil => { NSLocalizedFailureReason = "No APNS token specified before fetching FCM Token"; } 10.10.0 - [FirebaseMessaging][I-FCM002022] APNS device token not set before retrieving FCM Token for Sender ID '[redacted]'.Be sure to re-retrieve the FCM token once the APNS device token is set. 10.10.0 - [FirebaseMessaging][I-FCM002022] Declining request for FCM Token since no APNS Token specified flutter: FIREBASE_MESSAGING===> flutter: [firebase_messaging/unknown] An unknown error has occurred. [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)"" ```

Flutter doctor

Click to expand
[βœ“] Flutter (Channel stable, 3.10.6, on macOS 14.3 23D56 darwin-arm64, locale en-NP)
[βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[βœ“] Xcode - develop for iOS and macOS (Xcode 15.2)
[βœ—] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[βœ“] Android Studio (version 2021.3)
[βœ“] VS Code (version 1.87.0-insider)
[βœ“] Connected device (2 available)
[βœ“] Network resources

! Doctor found issues in 1 category.


Flutter dependencies

Details
Dart SDK 3.0.6
Flutter SDK 3.10.6
[project_name_and_version_redacted]

dependencies:
- android_path_provider 0.3.0 [flutter]
- carousel_slider 4.2.1 [flutter]
- cupertino_icons 1.0.5
- device_info_plus 9.0.3 [device_info_plus_platform_interface ffi file flutter flutter_web_plugins meta win32 win32_registry]
- dio 5.2.1+1 [async http_parser meta path]
- equatable 2.0.5 [collection meta]
- firebase_core 2.14.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_messaging 14.6.4 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- flutter 0.0.0 [characters collection js material_color_utilities meta vector_math sky_engine]
- flutter_bloc 8.1.3 [bloc flutter provider]
- flutter_html 3.0.0-beta.2 [html csslib collection list_counter flutter]
- flutter_local_notifications 15.1.1 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_spinkit 5.2.0 [flutter]
- geocoding 2.1.0 [flutter geocoding_platform_interface geocoding_android geocoding_ios]
- geolocator 9.0.2 [flutter geolocator_platform_interface geolocator_android geolocator_apple geolocator_web geolocator_windows]
- http 0.13.5 [async http_parser meta path]
- internet_file 1.2.0 [http path universal_file]
- loading_overlay 0.3.0 [flutter]
- math_expressions 2.4.0 [vector_math]
- open_filex 4.3.2 [flutter ffi]
- overlay_support 2.1.0 [flutter async]
- path_provider 2.0.15 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows]
- pdfx 2.4.0 [flutter flutter_web_plugins plugin_platform_interface js device_info_plus uuid meta extension synchronized universal_platform photo_view vector_math]
- permission_handler 10.4.1 [flutter meta permission_handler_android permission_handler_apple permission_handler_windows permission_handler_platform_interface]
- scroll_snap_list 0.9.1 [flutter]
- sqflite 2.2.8+4 [flutter sqflite_common path]
- syncfusion_flutter_gauges 20.4.54 [flutter syncfusion_flutter_core intl]
- url_launcher 6.1.11 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]

dev dependencies:
- flutter_launcher_icons 0.13.1 [args checked_yaml cli_util image json_annotation path yaml]
- flutter_native_splash 2.3.1 [args flutter flutter_web_plugins js html image meta path universal_io xml yaml]
- flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters collection js matcher material_color_utilities meta source_span stream_channel string_scanner term_glyph]
- melos 3.1.0 [ansi_styles args cli_launcher cli_util collection conventional_commit file glob graphs http meta mustache_template path platform pool prompts pub_semver pub_updater pubspec string_scanner yaml yaml_edit]

transitive dependencies:
- _flutterfire_internals 1.3.3 [collection firebase_core firebase_core_platform_interface flutter meta]
- ansi_styles 0.3.2+1
- archive 3.3.7 [crypto path pointycastle]
- args 2.4.1
- async 2.11.0 [collection meta]
- bloc 8.1.2 [meta]
- boolean_selector 2.1.1 [source_span string_scanner]
- characters 1.3.0
- charcode 1.3.1
- checked_yaml 2.0.2 [json_annotation source_span yaml]
- cli_launcher 0.3.1 [path yaml]
- cli_util 0.4.0 [meta path]
- clock 1.1.1
- collection 1.17.1
- conventional_commit 0.6.0+1
- convert 3.1.1 [typed_data]
- crypto 3.0.2 [typed_data]
- csslib 0.17.2 [source_span]
- dbus 0.7.8 [args ffi meta xml]
- device_info_plus_platform_interface 7.0.0 [flutter meta plugin_platform_interface]
- extension 0.6.0 [meta]
- fake_async 1.3.1 [clock collection]
- ffi 2.0.2
- file 6.1.4 [meta path]
- firebase_core_platform_interface 4.8.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.6.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_messaging_platform_interface 4.5.3 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.5.3 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- flutter_local_notifications_linux 4.0.0+1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories]
- flutter_local_notifications_platform_interface 7.0.0+1 [flutter plugin_platform_interface]
- flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta vector_math]
- geocoding_android 2.1.0 [flutter geocoding_platform_interface]
- geocoding_ios 2.1.0 [flutter geocoding_platform_interface]
- geocoding_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- geolocator_android 4.2.0 [flutter geolocator_platform_interface uuid]
- geolocator_apple 2.2.7 [flutter geolocator_platform_interface]
- geolocator_platform_interface 4.0.7 [flutter plugin_platform_interface vector_math meta]
- geolocator_web 2.1.6 [flutter flutter_web_plugins geolocator_platform_interface]
- geolocator_windows 0.1.1 [flutter geolocator_platform_interface]
- glob 2.1.2 [async collection file path string_scanner]
- graphs 2.3.1 [collection]
- html 0.15.3 [csslib source_span]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- image 4.0.17 [archive meta xml]
- intl 0.18.1 [clock meta path]
- io 1.0.4 [meta path string_scanner]
- js 0.6.7 [meta]
- json_annotation 4.8.0 [meta]
- list_counter 1.0.2
- matcher 0.12.15 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.2.0
- meta 1.9.1
- mustache_template 2.0.0
- nested 1.0.0 [flutter]
- path 1.8.3
- path_provider_android 2.0.27 [flutter path_provider_platform_interface]
- path_provider_foundation 2.2.3 [flutter path_provider_platform_interface]
- path_provider_linux 2.1.11 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_platform_interface 2.0.6 [flutter platform plugin_platform_interface]
- path_provider_windows 2.1.7 [ffi flutter path path_provider_platform_interface win32]
- permission_handler_android 10.3.0 [flutter permission_handler_platform_interface]
- permission_handler_apple 9.1.3 [flutter permission_handler_platform_interface]
- permission_handler_platform_interface 3.11.0+1 [flutter meta plugin_platform_interface]
- permission_handler_windows 0.1.3 [flutter permission_handler_platform_interface]
- petitparser 5.4.0 [meta]
- photo_view 0.14.0 [flutter]
- platform 3.1.0
- plugin_platform_interface 2.1.4 [meta]
- pointycastle 3.7.3 [collection convert js]
- pool 1.5.1 [async stack_trace]
- process 4.2.4 [file path platform]
- prompts 2.0.0 [charcode io]
- provider 6.0.5 [collection flutter nested]
- pub_semver 2.1.4 [collection meta]
- pub_updater 0.2.4 [http json_annotation process]
- pubspec 2.3.0 [path pub_semver yaml uri]
- quiver 3.2.1 [matcher]
- sky_engine 0.0.99
- source_span 1.9.1 [collection path term_glyph]
- sqflite_common 2.4.5+1 [synchronized path meta]
- stack_trace 1.11.0 [path]
- stream_channel 2.1.1 [async]
- string_scanner 1.2.0 [source_span]
- syncfusion_flutter_core 20.4.54 [vector_math flutter]
- synchronized 3.1.0
- term_glyph 1.2.1
- test_api 0.5.1 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph matcher]
- timezone 0.9.2 [path]
- typed_data 1.3.2 [collection]
- universal_file 1.0.0 [meta]
- universal_io 2.2.2 [collection meta typed_data]
- universal_platform 1.0.0+1
- uri 1.0.0 [matcher quiver]
- url_launcher_android 6.0.36 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.1.4 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.0.5 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.0.5 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.1.3 [flutter plugin_platform_interface]
- url_launcher_web 2.0.18 [flutter flutter_web_plugins url_launcher_platform_interface]
- url_launcher_windows 3.0.6 [flutter url_launcher_platform_interface]
- uuid 3.0.7 [crypto]
- vector_math 2.1.4
- win32 5.0.5 [ffi]
- win32_registry 1.1.1 [ffi win32]
- xdg_directories 1.0.0 [meta path process]
- xml 6.3.0 [collection meta petitparser]
- yaml 3.1.2 [collection source_span string_scanner]
- yaml_edit 2.1.1 [collection meta source_span yaml]

praveengitsit-pro avatar Feb 06 '24 18:02 praveengitsit-pro

Thanks for the details and your patience while we figure this out @praveengitsit-pro Can you verify if this only occurs on device or while running on simulator too ? That'll narrow down the issue occurs on both or is specific to either simulator or physical device.

darshankawar avatar Feb 07 '24 10:02 darshankawar

@praveengitsit-pro can you confirm if firebase is connected with apple.

"So in order to get Firebase push notifications to work, you need to create an APNs authentication key and add it to Firebase. Luckily this is simple to do. Log into your Apple Developer account, then under Certificates, Identifiers & Profiles click on Keys. Click the + button to register a new key."

flakerimi avatar Feb 07 '24 10:02 flakerimi

@darshankawar I thought the Push Notifications feature were something to be tested on a physical device so hadn't given it much thought lately. To my utter surprise, the codebase works in iPhone 14 - iOS 16.4 simulator, meaning I receive both the APNS token as well as the FCM token. I did do one following change to my Podfile though.

# Uncomment this line to define a global platform for your project
platform :ios, '12.0'

@flakerimi Not sure what you mean by confirming the connection but I have double-checked my APNS key and Firebase setup. It is also mentioned in the original issue.

praveengitsit-pro avatar Feb 07 '24 12:02 praveengitsit-pro

To my utter surprise, the codebase works in iPhone 14 - iOS 16.4 simulator, meaning I receive both the APNS token as well as the FCM token

That is correct. This is from xcode 14 release notes.

Reiterating this as it was also backed by the team to be the solution.

darshankawar avatar Feb 09 '24 12:02 darshankawar

Adding a one-second delay just before calling "getAPNSToken" seems to correct the problem. Below that, no (tested with 500 milliseconds). But... 1 second is a lot and doesn't seem right...

On top of that, it worked fine without this delay a few weeks/months ago, and I haven't changed anything on this piece of code since...

smbpunt avatar Feb 13 '24 13:02 smbpunt

Hey @praveengitsit-pro. 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 avatar Feb 22 '24 02:02 google-oss-bot

@darshankawar

I am able to make the notifications work for iOS in a build for Test Flight, as well as in debug mode by directly connecting to my dev machine. The delay, as mentioned before, makes it work. (Tested on iPhone 15 Pro physical device)

Still facing issues building it for iPhone X in debug mode but I think I'll be moving on from this right now.

praveengitsit-pro avatar Feb 23 '24 13:02 praveengitsit-pro

Should we really close this ticket? Adding a one-second delay doesn't seem like a fix to me, but more like a workaround until the bug is properly addressed...

smbpunt avatar Feb 23 '24 13:02 smbpunt

@Punt13140 I agree with you that this is more a hack at the moment. I don't know if the team will be working on this anytime soon, but will keep it open until a proper resolve is addressed.

praveengitsit-pro avatar Feb 23 '24 14:02 praveengitsit-pro

this as also mentioned above earlier is a likely solution, but will keep the issue open and label for team's input / attention if this need another re-look.

darshankawar avatar Feb 26 '24 11:02 darshankawar

There is nothing we can do from our end, the APNS token is delivered to this delegate method, sometimes it arrives quickly, sometimes not. You have to design your app in a way that ensures it has arrived before making firebase messaging API calls. A Completer is useful in this scenario: https://api.flutter.dev/flutter/dart-async/Completer-class.html

russellwheatley avatar Feb 28 '24 15:02 russellwheatley

There is nothing we can do from our end, the APNS token is delivered to this delegate method, sometimes it arrives quickly, sometimes not. You have to design your app in a way that ensures it has arrived before making firebase messaging API calls. A Completer is useful in this scenario: api.flutter.dev/flutter/dart-async/Completer-class.html

Is this really a recommended approach? Design our apps to wait somehow (how long and when?) and hope that token will be available.

We are initializing Firebase Messaging on application startup and cant block user's flow by some magic constant delay to make notifications work.

I don't have knowledge about native's ios part, but is there really no way to system tell us that token is available though callback or similar?

petrnymsa avatar Mar 13 '24 15:03 petrnymsa

Any update?

DmitriySimonov avatar Mar 27 '24 08:03 DmitriySimonov

I got same erorr, but it fixed after upgrate my iphone to last iOS. Error still here, but push notifications are work

ivanbogomoloff avatar Mar 29 '24 11:03 ivanbogomoloff

You can update the "AppDelegate.swift" like that

import UIKit
import Flutter
import FirebaseCore
import FirebaseMessaging

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

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

ramazans avatar Mar 29 '24 23:03 ramazans