firebase / flutterfire

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

šŸ› [firebase_messaging] Background Handler not exiting on iOS #6184

Closed vishal-android-freak closed 1 year ago

vishal-android-freak commented 3 years ago

Bug report

Describe the bug I am testing a usecase in my app where I send a silent notification to the app and retrieve messages from my backend over HTTP. Once they are retrieved, I send a POST request with the message IDs to delete the messages from the DB. Now, as soon as the app goes in the background, this entire cycle works perfectly fine till the time I see this popping up in the logs:

BackgroundTask] Background Task 16 ("Flutter debug task"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

I searched online to see what does this means and I understood from some comments in the flutter engine code that this task runs to ensure the app can hot reload and do other tasks when the device locks and comes back (I hope this is right). But right after this log, I get an error that says

BackgroundSession <C80785BD-8961-43DE-BF2F-6CE61F974981> connection to background transfer daemon interrupted
BackgroundSession <C80785BD-8961-43DE-BF2F-6CE61F974981> connection to background transfer daemon invalidated
dnssd_clientstub read_all(17) DEFUNCT
[VERBOSE-2:FlutterObservatoryPublisher.mm(143)] Could not register as server for FlutterObservatoryPublisher. Check your network settings and relaunch the application.
dnssd_clientstub read_all(18) DEFUNCT
[VERBOSE-2:FlutterObservatoryPublisher.mm(143)] Could not register as server for FlutterObservatoryPublisher. Check your network settings and relaunch the application.
[connection] nw_read_request_report [C2] Receive failed with error "Software caused connection abort"

Post which, for every new notification that comes in, I see this error in logs

dnssd_clientstub write_all(25) DEFUNCT
dnssd_clientstub deliver_request ERROR: write_all(25, 62 bytes) failed
dnssd_clientstub write_all(25) DEFUNCT

And the most weird thing is, my HTTP requests for fetching data from the server works fine. Data is retrieved and I show notification to the user locally, but the POST request to delete the messages gets stuck. After some time the app crashes in the background with an error

[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: OperationException(linkException: ServerException(originalException: HandshakeException: Connection terminated during handshake, parsedResponse: null), graphqlErrors: [])

I observed that even if I don't do any processing in the background handler of FCM and keep the function blank, I still see the following error

BackgroundTask] Background Task 16 ("Flutter debug task"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

Can you guys help me understand what is happening? This works perfectly on Android and all the HTTP requests are perfectly fetched and executed. iOS behavior is weird. Why is the background processing not getting completed on iOS after the execution of HTTP requests is completed?

Expected behavior

All the HTTP requests should work as expected.

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, 2.0.6, on macOS 11.3.1 20E241 darwin-x64, locale en-IN) [āœ“] Android toolchain - develop for Android devices (Android SDK version 30.0.3) [āœ“] Xcode - develop for iOS and macOS [āœ“] Chrome - develop for the web [āœ“] Android Studio (version 4.1) [āœ“] VS Code (version 1.56.2) [āœ“] Connected device (3 available) ```

Flutter dependencies

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

Click To Expand ``` Dart SDK 2.12.3 Flutter SDK 2.0.6 rego 0.4.0+18 dependencies: - age_calculator 1.0.0 [flutter] - audioplayers 0.18.3 [uuid path_provider flutter flutter_web_plugins] - auto_size_text 3.0.0-nullsafety.0 [flutter] - bottom_sheet_x 1.0.0 [flutter] - cached_network_image 3.1.0-alpha.1 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web] - chat_pickers 0.2.2 [flutter http giphy_client shared_preferences material_design_icons_flutter emoji_picker flutter_hooks universal_io] - chewie 1.0.0 [cupertino_icons flutter video_player wakelock] - connectivity 3.0.3 [flutter meta connectivity_platform_interface connectivity_macos connectivity_for_web] - cryptography 2.0.1 [collection crypto fixnum js meta typed_data] - cupertino_icons 1.0.3 - dart_date 1.1.0 [intl timeago] - dotted_border 2.0.0 [flutter path_drawing] - dotted_line 3.0.0 [flutter] - duration 3.0.6 - enum_to_string 2.0.1 - file_picker 3.0.1 [flutter flutter_web_plugins flutter_plugin_android_lifecycle plugin_platform_interface] - firebase_analytics 8.0.4 [firebase_analytics_platform_interface firebase_analytics_web firebase_core flutter meta] - firebase_auth 1.1.4 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta] - firebase_core 1.1.1 [firebase_core_platform_interface firebase_core_web flutter meta] - firebase_in_app_messaging 0.5.0+3 [firebase_core flutter meta] - firebase_messaging 9.1.4 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta] - firebase_remote_config 0.10.0-dev.3 [firebase_core firebase_core_platform_interface firebase_remote_config_platform_interface flutter] - firebase_storage 8.0.6 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter] - floor 1.1.0 [floor_annotation flutter meta path sqflite sqflite_common_ffi] - flutter 0.0.0 [characters collection meta typed_data vector_math sky_engine] - flutter_keyboard_visibility 5.0.2 [meta flutter_keyboard_visibility_platform_interface flutter_keyboard_visibility_web flutter] - flutter_local_notifications 5.0.0+4 [flutter flutter_local_notifications_platform_interface platform timezone] - flutter_parsed_text 2.2.0 [flutter] - flutter_secure_storage 4.2.0 [meta flutter] - flutter_svg 0.22.0 [flutter meta path_drawing vector_math xml] - flutter_uploader 3.0.0-beta.1 [equatable flutter] - fluttertoast 8.0.6 [flutter flutter_web_plugins] - graphql_flutter 5.0.0-nullsafety.2 [graphql gql_exec flutter meta path_provider path connectivity hive plugin_platform_interface] - image_cropper 1.4.0 [flutter] - image_picker 0.7.5 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface image_picker_for_web] - image_size_getter 1.0.0 [collection hashcodes] - intl 0.17.0 [clock path] - intl_phone_number_input 0.7.0+2 [flutter meta libphonenumber_plugin equatable collection] - introduction_screen 1.0.9 [flutter dots_indicator] - isolate_handler 1.0.0 [flutter flutter_isolate] - logger 1.0.0 - messagepack 0.2.1 - mqtt_client 9.3.1 [typed_data event_bus path crypto meta] - objectid 2.0.0 - package_info 2.0.0 [flutter] - path 1.8.0 - path_provider 2.0.1 [flutter path_provider_platform_interface path_provider_macos path_provider_linux path_provider_windows] - photofilters 2.0.2 [flutter image meta path_provider] - pin_code_fields 7.1.0 [flutter] - pinenacl 0.2.0 - progress_state_button 1.0.3 [flutter] - provider 5.0.0 [collection flutter nested] - qr_code_scanner 0.4.0 [flutter] - qr_flutter 4.0.0 [flutter qr] - quiver 3.0.1 [matcher] - receive_sharing_intent 1.4.5 [flutter] - record 2.1.1 [flutter] - rxdart 0.26.0 - scroll_snap_list 0.8.0 [flutter] - sentry_flutter 5.0.0 [flutter flutter_web_plugins sentry package_info_plus] - share 2.0.1 [meta mime flutter] - shared_preferences 2.0.5 [meta flutter shared_preferences_platform_interface shared_preferences_linux shared_preferences_macos shared_preferences_web shared_preferences_windows] - sliding_up_panel 2.0.0+1 [flutter] - state_persistence 0.1.0 [path path_provider flutter] - swipe_to 0.1.0-nullsafety.1 [flutter] - theme_provider 0.5.0 [flutter shared_preferences] - url_launcher 6.0.3 [flutter url_launcher_platform_interface url_launcher_linux url_launcher_macos url_launcher_windows url_launcher_web] - video_player 2.1.1 [meta video_player_platform_interface video_player_web flutter flutter_test] - video_thumbnail 0.3.3 [flutter] dev dependencies: - build_runner 2.0.2 [args async analyzer 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 pedantic pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml] - floor_generator 1.1.0 [analyzer build build_config code_builder collection floor_annotation meta source_gen] - flutter_launcher_icons 0.9.0 [args image path yaml] - flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher meta source_span stream_channel string_scanner term_glyph typed_data] dependency overrides: - http 0.13.3 [async http_parser meta path pedantic] - path_provider 2.0.1 [flutter path_provider_platform_interface path_provider_macos path_provider_linux path_provider_windows] - shared_preferences 2.0.5 [meta flutter shared_preferences_platform_interface shared_preferences_linux shared_preferences_macos shared_preferences_web shared_preferences_windows] transitive dependencies: - _fe_analyzer_shared 21.0.0 [meta] - analyzer 1.5.0 [_fe_analyzer_shared cli_util collection convert crypto glob meta package_config path pub_semver source_span watcher yaml pedantic] - archive 3.1.2 [crypto path] - args 2.0.0 - async 2.5.0 [collection] - boolean_selector 2.1.0 [source_span string_scanner] - build 2.0.1 [analyzer async convert crypto glob logging meta path] - build_config 1.0.0 [checked_yaml json_annotation path pubspec_parse yaml] - build_daemon 3.0.0 [built_collection built_value http_multi_server logging pedantic path pool shelf shelf_web_socket stream_transform watcher web_socket_channel] - build_resolvers 2.0.1 [analyzer build crypto graphs logging path package_config pool pub_semver stream_transform] - build_runner_core 7.0.0 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta path package_config pedantic pool timing watcher yaml] - built_collection 5.0.0 - built_value 8.0.6 [built_collection collection fixnum] - cached_network_image_platform_interface 1.0.0-alpha.0 [flutter flutter_cache_manager] - cached_network_image_web 1.0.0-alpha.0 [flutter flutter_cache_manager cached_network_image_platform_interface] - characters 1.1.0 - charcode 1.2.0 - checked_yaml 2.0.1 [json_annotation source_span yaml] - cli_util 0.3.0 [meta path] - clock 1.1.0 - code_builder 4.0.0 [built_collection built_value collection matcher meta] - collection 1.15.0 - connectivity_for_web 0.4.0 [connectivity_platform_interface flutter_web_plugins flutter] - connectivity_macos 0.2.0 [flutter] - connectivity_platform_interface 2.0.0 [flutter meta plugin_platform_interface] - convert 3.0.0 [typed_data] - crypto 3.0.1 [collection typed_data] - dart_style 2.0.1 [analyzer args path pub_semver source_span] - dots_indicator 1.2.0 [flutter] - emoji_picker 0.1.0 [flutter shared_preferences] - equatable 2.0.0 [collection meta] - event_bus 2.0.0 - fake_async 1.2.0 [clock collection] - ffi 1.0.0 - file 6.0.0 [meta path] - firebase 9.0.1 [http http_parser js] - firebase_analytics_platform_interface 2.0.1 [flutter meta] - firebase_analytics_web 0.3.0+1 [firebase firebase_analytics_platform_interface flutter flutter_web_plugins meta] - firebase_auth_platform_interface 4.2.2 [firebase_core flutter meta plugin_platform_interface] - firebase_auth_web 1.1.2 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser intl js meta] - firebase_core_platform_interface 4.0.1 [collection flutter meta plugin_platform_interface] - firebase_core_web 1.0.3 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - firebase_messaging_platform_interface 2.1.4 [firebase_core flutter meta plugin_platform_interface] - firebase_messaging_web 1.0.7 [firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta] - firebase_remote_config_platform_interface 0.3.0-dev.3 [firebase_core flutter meta plugin_platform_interface] - firebase_storage_platform_interface 2.0.4 [collection firebase_core flutter meta plugin_platform_interface] - firebase_storage_web 1.0.6 [async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http js meta] - fixnum 1.0.0 - floor_annotation 1.0.0 [meta] - flutter_blurhash 0.6.0 [flutter meta pedantic] - flutter_cache_manager 3.0.2 [clock collection file flutter http image path path_provider pedantic rxdart sqflite uuid] - flutter_hooks 0.15.0 [flutter] - flutter_isolate 2.0.0 [flutter uuid] - 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_local_notifications_platform_interface 3.0.0 [flutter plugin_platform_interface] - flutter_plugin_android_lifecycle 2.0.1 [flutter] - flutter_web_plugins 0.0.0 [flutter js characters collection meta typed_data vector_math] - frontend_server_client 2.1.0 [async path] - giphy_client 0.2.0 [meta http] - glob 2.0.1 [async collection file path pedantic string_scanner] - gql 0.13.0-nullsafety.2 [collection meta source_span] - gql_dedupe_link 2.0.0-nullsafety.1 [meta gql_exec gql_link async] - gql_error_link 0.2.0-nullsafety.1 [async gql_exec gql_link meta] - gql_exec 0.3.0-nullsafety.2 [collection meta gql] - gql_http_link 0.4.0-nullsafety.1 [meta gql gql_exec gql_link http http_parser] - gql_link 0.4.0-nullsafety.3 [meta gql gql_exec] - gql_transform_link 0.2.0-nullsafety.1 [gql_exec gql_link] - graphql 5.0.0-nullsafety.4 [meta path gql gql_exec gql_link gql_http_link gql_transform_link gql_error_link gql_dedupe_link hive normalize http collection web_socket_channel stream_channel rxdart uuid] - graphs 2.0.0 - hashcodes 2.0.0 - hive 2.0.4 [meta crypto] - http_multi_server 3.0.1 [async] - http_parser 4.0.0 [charcode collection source_span string_scanner typed_data] - image 3.0.2 [archive meta xml] - image_picker_for_web 2.0.0 [image_picker_platform_interface meta flutter flutter_web_plugins] - image_picker_platform_interface 2.1.0 [flutter meta http plugin_platform_interface] - io 1.0.0 [meta path string_scanner] - js 0.6.3 - json_annotation 4.0.1 - libphonenumber 2.0.0 [flutter meta] - libphonenumber_platform_interface 0.3.1 [flutter plugin_platform_interface] - libphonenumber_plugin 0.2.3 [flutter flutter_web_plugins libphonenumber_platform_interface libphonenumber_web libphonenumber] - libphonenumber_web 0.2.0+1 [flutter flutter_web_plugins js libphonenumber_platform_interface] - logging 1.0.1 - matcher 0.12.10 [stack_trace] - material_design_icons_flutter 4.0.5955 [flutter] - meta 1.3.0 - mime 1.0.0 - nested 1.0.0 [flutter] - normalize 0.5.1 [gql collection] - octo_image 1.0.0+1 [flutter flutter_blurhash] - package_config 2.0.0 [path] - package_info_plus 1.0.1 [flutter package_info_plus_platform_interface package_info_plus_linux package_info_plus_macos package_info_plus_windows package_info_plus_web] - package_info_plus_linux 1.0.1 [package_info_plus_platform_interface flutter path] - package_info_plus_macos 1.1.1 [flutter] - package_info_plus_platform_interface 1.0.1 [flutter meta plugin_platform_interface] - package_info_plus_web 1.0.1 [http package_info_plus_platform_interface flutter flutter_web_plugins meta] - package_info_plus_windows 1.0.1 [package_info_plus_platform_interface ffi flutter win32] - path_drawing 0.5.1 [vector_math meta path_parsing flutter] - path_parsing 0.2.1 [vector_math meta] - path_provider_linux 2.0.0 [path xdg_directories path_provider_platform_interface flutter] - path_provider_macos 2.0.0 [flutter] - path_provider_platform_interface 2.0.1 [flutter meta platform plugin_platform_interface] - path_provider_windows 2.0.1 [path_provider_platform_interface meta path flutter ffi win32] - pedantic 1.11.0 - petitparser 4.1.0 [meta] - platform 3.0.0 - plugin_platform_interface 2.0.0 [meta] - pool 1.5.0 [async stack_trace] - process 4.0.0 [file path platform] - pub_semver 2.0.0 [collection] - pubspec_parse 1.0.0 [checked_yaml collection json_annotation pub_semver yaml] - qr 2.0.0 [meta] - sentry 5.0.0 [http meta stack_trace uuid] - shared_preferences_linux 2.0.0 [flutter file meta path path_provider_linux shared_preferences_platform_interface] - shared_preferences_macos 2.0.0 [shared_preferences_platform_interface flutter] - shared_preferences_platform_interface 2.0.0 [flutter] - shared_preferences_web 2.0.0 [shared_preferences_platform_interface flutter flutter_web_plugins meta] - shared_preferences_windows 2.0.0 [shared_preferences_platform_interface flutter file meta path path_provider_platform_interface path_provider_windows] - shelf 1.1.2 [async collection http_parser path stack_trace stream_channel] - shelf_web_socket 1.0.1 [shelf stream_channel web_socket_channel] - sky_engine 0.0.99 - source_gen 1.0.0 [analyzer async build dart_style glob meta path pedantic source_span] - source_span 1.8.0 [charcode collection path term_glyph] - sqflite 2.0.0+3 [flutter sqflite_common path] - sqflite_common 2.0.0+2 [synchronized path meta] - sqflite_common_ffi 2.0.0 [sqlite3 sqflite_common synchronized path meta] - sqlite3 1.1.1 [collection ffi meta] - stack_trace 1.10.0 [path] - stream_channel 2.1.0 [async] - stream_transform 2.0.0 - string_scanner 1.1.0 [charcode source_span] - synchronized 3.0.0 - term_glyph 1.2.0 - test_api 0.2.19 [async boolean_selector collection meta path source_span stack_trace stream_channel string_scanner term_glyph matcher] - timeago 3.0.2 - timezone 0.7.0 [path] - timing 1.0.0 [json_annotation] - typed_data 1.3.0 [collection] - universal_io 1.0.1 [meta zone_local] - url_launcher_linux 2.0.0 [flutter] - url_launcher_macos 2.0.0 [flutter] - url_launcher_platform_interface 2.0.1 [flutter plugin_platform_interface] - url_launcher_web 2.0.0 [url_launcher_platform_interface meta flutter flutter_web_plugins] - url_launcher_windows 2.0.0 [flutter] - uuid 3.0.4 [crypto] - vector_math 2.1.0 - video_player_platform_interface 4.1.0 [flutter meta flutter_test] - video_player_web 2.0.0 [flutter flutter_web_plugins meta video_player_platform_interface] - wakelock 0.4.0 [flutter meta wakelock_macos wakelock_platform_interface wakelock_web] - wakelock_macos 0.1.0 [flutter flutter_web_plugins wakelock_platform_interface] - wakelock_platform_interface 0.2.0 [flutter meta] - wakelock_web 0.2.0 [flutter flutter_web_plugins js wakelock_platform_interface] - watcher 1.0.0 [async path pedantic] - web_socket_channel 2.1.0 [async crypto stream_channel] - win32 2.0.5 [ffi] - xdg_directories 0.2.0 [meta path process] - xml 5.1.0 [collection meta petitparser] - yaml 3.1.0 [collection source_span string_scanner] - zone_local 0.1.2 ```

darshankawar commented 3 years ago

@vishal-android-freak Thanks for the detailed report. Can you provide handler for background messages ? Is this behavior occuring for with and without data notifications ?

Specially on iOS, you need to manually open the app again for the notifications to show up. May be try this case ?

vishal-android-freak commented 3 years ago

@darshankawar We are only using data-only notifications throughout the app. Here is my background handler:

Future<void> _firebaseBackgroundMessageHandler(RemoteMessage message) async {
  WidgetsFlutterBinding.ensureInitialized();
  final common = Platform.isAndroid ? await _init() : Common.instance;
  common.logDebug("bg called");
  if (message.data.containsKey("CONFIG_STATE")) {
    common.saveStatus("CONFIG_STATE", "STALE");
  } else if (message.data.containsKey('type')) {
    if (Platform.isAndroid) {
      await _initForBGMessages();
    }

    final offlineMessages = await _getBackgroundMessages(common);

    FlutterNotifications.FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterNotifications.FlutterLocalNotificationsPlugin();

    final userDetails = UserDetails.instance;
    RegoCouple couple = (userDetails.couple)!;

    final myself = FlutterNotifications.Person(bot: false, key: couple.self!.uniqueId, name: couple.self!.name);
    final partner = FlutterNotifications.Person(bot: false, key: couple.partner!.uniqueId, name: couple.partner!.name);

    List<Future<void>> messageInsertFutures = [];

    offlineMessages.forEach((ChatMessage message) {
      messageInsertFutures.add(common.saveNotificationMessage(
          FlutterNotifications.Message(message.message!, DateTime.parse(message.timestamp!).toLocal(), partner)));
    });

    await Future.wait(messageInsertFutures);

    final messages = await common.getNotificationMessages(partner);

    final messagingStyleInformation = FlutterNotifications.MessagingStyleInformation(myself,
        groupConversation: false,
        conversationTitle: '${messages.length} New Message${messages.length > 1 ? 's' : ''}',
        htmlFormatContent: true,
        htmlFormatTitle: true,
        messages: messages);

    final androidPlatformChannelSpecifics = FlutterNotifications.AndroidNotificationDetails(
        'com.rego.rego', 'ReGo Chat Notifications', 'Notification channel for chat messages',
        importance: FlutterNotifications.Importance.max,
        priority: FlutterNotifications.Priority.high,
        showWhen: true,
        styleInformation: messagingStyleInformation);

    const FlutterNotifications.IOSNotificationDetails iOSPlatformChannelSpecifics =
        FlutterNotifications.IOSNotificationDetails(threadIdentifier: 'rego-chat', presentBadge: true);

    final notficationDetails = FlutterNotifications.NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);

    if (Platform.isIOS) {
      offlineMessages.forEach((message) {
        flutterLocalNotificationsPlugin.show(message.id.hashCode, partner.name, message.message, notficationDetails,
            payload: 'chat');
      });
    } else {
      flutterLocalNotificationsPlugin.show(99, 'ReGo', '', notficationDetails, payload: 'chat');
    }
  }
}

Future<List<ChatMessage>> _getBackgroundMessages(Common common) async {
  final repository = HomeRepository();
  final keyHandler = EncryptionKeyHandler.instance;
  final coupleBox = UserDetails.instance.couple!;
  final localUserRegoId = coupleBox.self!.uniqueId!;
  final partnerRegoId = coupleBox.partner!.uniqueId!;

   // This is the HTTP request which is functioning properly
  Map<String, dynamic> messageData =
      await _getMessagesFromDB(common, repository, keyHandler, localUserRegoId, partnerRegoId);
  List<ChatMessage> offlineChatMessages = List<ChatMessage>.from(messageData['messages']);
  List<String> messageIds = List<String>.from(messageData['messageIds']);
  List<ChatMessage> deliveryReportMessages = [];

  if (offlineChatMessages.isNotEmpty) {
    offlineChatMessages.forEach((message) {
      if (!message.isSelf! &&
          message.messageType != MessageType.DELIVERY_REPORT &&
          message.messageType != MessageType.REACTION &&
          message.messageType != MessageType.DELETE_REQUEST) {
        message.deliveryStatus = DeliveryStatus.DELIVERED;
        deliveryReportMessages.add(message);
      }
      if (message.messageType == MessageType.DELETE_REQUEST) {
        _deleteChatMessage(message, repository);
      }
    });
    repository.insertOfflineMessages(
        offlineChatMessages.where((message) => message.messageType != MessageType.DELETE_REQUEST).toList());
  }

  final List<Map<String, dynamic>> encryptedDeliveryReports =
      _getEncryptedDeliveryReports(deliveryReportMessages, keyHandler, localUserRegoId, partnerRegoId);

  if (messageIds.isNotEmpty) {
   // This is the delete HTTP post request which is getting stuck and crashing with a handshake error
    repository.deleteMessagesAndUpdateDeliveryReports(
        common.getSimpleGraphQLClient(), messageIds, encryptedDeliveryReports);
  }
  return offlineChatMessages
      .where((message) => (!message.isSelf! &&
          message.messageType != MessageType.DELIVERY_REPORT &&
          message.messageType != MessageType.REACTION &&
          message.messageType != MessageType.DELETE_REQUEST))
      .toList();
}

Specially on iOS, you need to manually open the app again for the notifications to show up. May be try this case ?

I get notifications in the background but I am not able to do any HTTP POST request after 30 secs

darshankawar commented 3 years ago

Keeping this issue open for further investigation.

vishal-android-freak commented 3 years ago

Any update on this? This is a serious issue that is stopping us from releasing the iOS version.

menakalakshan commented 3 years ago

Any update guys? .. I am also stuck at this point

nongtiny commented 3 years ago

I think we need to stop the background task when the HTTP request or your background handler is done, but the problem is how can we get the background task ID.

From what I see in the error, it said Remember to call UIApplication.endBackgroundTask(_:). This function argument accepts the UIBackgroundTaskIdentifier doc: https://developer.apple.com/documentation/uikit/uiapplication/1622970-endbackgroundtask

I think we have to create a method channel to trigger this function from the native iOS side, but the problem is I don't know how can get a background task identifier for that task.

vishal-android-freak commented 2 years ago

@darshankawar any update on this?

Lyokone commented 1 year ago

Looking at the code we properly call the endBackgroundTask

completionHandler(UIBackgroundFetchResultNewData);
                if (backgroundTaskId != UIBackgroundTaskInvalid) {
                  [application endBackgroundTask:backgroundTaskId];
                  backgroundTaskId = UIBackgroundTaskInvalid;
                }

Are you sure that your code doesn't hang for longer than 30s?

google-oss-bot commented 1 year ago

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

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

google-oss-bot commented 1 year ago

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

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