diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index b594b24e5..758e0a42a 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -50,6 +50,47 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin { } } +/// Keeps the app running while the main isolate handles a notification +/// action, until Dart reports it as handled +private final class NotificationActionTasks: NSObject, FlutterPlugin { + static let pluginName = "NotificationActionTasks" + private static let channelName = "de.wger.flutter/notification_actions" + /// Upper bound if Dart never reports back, e.g. without a running workout + private static let timeout: TimeInterval = 20 + private static var tasks: [UIBackgroundTaskIdentifier] = [] + + static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(NotificationActionTasks(), channel: channel) + } + + static func begin() { + var task: UIBackgroundTaskIdentifier = .invalid + task = UIApplication.shared.beginBackgroundTask { end(task) } + tasks.append(task) + DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { end(task) } + } + + private static func end(_ task: UIBackgroundTaskIdentifier) { + guard let index = tasks.firstIndex(of: task) else { + return + } + tasks.remove(at: index) + UIApplication.shared.endBackgroundTask(task) + } + + func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + guard call.method == "actionHandled" else { + result(FlutterMethodNotImplemented) + return + } + for task in Self.tasks { + Self.end(task) + } + result(nil) + } +} + @main @objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { override func application( @@ -62,24 +103,13 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin { } // A notification action is handled by the main isolate, but the plugin - // completes the response right away and iOS suspends the app again. - // Keep it running briefly so the action is processed now. + // completes the response right away and iOS suspends the app again override func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { - var task: UIBackgroundTaskIdentifier = .invalid - task = UIApplication.shared.beginBackgroundTask { - UIApplication.shared.endBackgroundTask(task) - task = .invalid - } - DispatchQueue.main.asyncAfter(deadline: .now() + 10) { - if task != .invalid { - UIApplication.shared.endBackgroundTask(task) - task = .invalid - } - } + NotificationActionTasks.begin() super.userNotificationCenter( center, didReceive: response, withCompletionHandler: completionHandler) } @@ -90,6 +120,13 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin { GeneratedPluginRegistrant.register(with: registry) } GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + if let registrar = engineBridge.pluginRegistry.registrar( + forPlugin: NotificationActionTasks.pluginName + ) { + NotificationActionTasks.register(with: registrar) + } else { + NSLog("NotificationActionTasks registrar unavailable") + } guard let registrar = engineBridge.pluginRegistry.registrar( forPlugin: StorageExclusionPlugin.pluginName diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index 3b8a6f6e4..f2b254e07 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -127,6 +127,16 @@ class WorkoutNotificationController { /// Carries out a notification action. Stale actions only refresh the /// notification, without a running session the user is sent to the app. Future handleAction(String? actionId, String? encodedPayload) async { + try { + await _handleAction(actionId, encodedPayload); + } finally { + // Lets iOS suspend the app again once the notification is up to date + await _queue; + await _service.actionHandled(); + } + } + + Future _handleAction(String? actionId, String? encodedPayload) async { final state = _ref.read(gymStateProvider); if (!state.isInitialized) { // E.g. iOS started the app in the background just for this action diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 074cc0949..90dd70259 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -19,6 +19,7 @@ import 'dart:ui'; import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -84,6 +85,9 @@ abstract class WorkoutNotificationService { /// Removes the shown notification and a pending rest alarm Future cancelAll(); + + /// Lets the platform suspend the app again after an action + Future actionHandled(); } /// For platforms without workout notifications @@ -117,6 +121,9 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { @override Future cancelAll() async {} + + @override + Future actionHandled() async {} } /// Android and iOS, via flutter_local_notifications @@ -125,6 +132,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { static const _controlsChannelId = 'workout_controls'; static const _alarmChannelId = 'rest_alarm'; static const _restEndCategory = 'workout_rest_end'; + static const _actionTasksChannel = MethodChannel('de.wger.flutter/notification_actions'); final _logger = Logger('LocalWorkoutNotificationService'); final _plugin = FlutterLocalNotificationsPlugin(); @@ -226,6 +234,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ], ), iOS: DarwinNotificationDetails( + presentSound: true, categoryIdentifier: alarm.canLogSet ? _restEndCategory : null, ), ), @@ -295,6 +304,19 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { await _initialized; await _plugin.cancel(id: _notificationId); } + + @override + Future actionHandled() async { + // Only iOS holds the app awake for an action, see AppDelegate.swift + if (defaultTargetPlatform != TargetPlatform.iOS) { + return; + } + try { + await _actionTasksChannel.invokeMethod('actionHandled'); + } on PlatformException catch (e) { + _logger.warning('Could not end the background task: $e'); + } + } } /// Whether rest alarms fire on time, rechecked whenever it is shown again diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index 92b572131..4924148a8 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -56,6 +56,7 @@ void main() { when(service.scheduleRestAlarm(any, any)).thenAnswer((_) async {}); when(service.showControls(any, any)).thenAnswer((_) async {}); when(service.showNotLogged(any)).thenAnswer((_) async {}); + when(service.actionHandled()).thenAnswer((_) async {}); when(service.initialize(any, onTap: anyNamed('onTap'))).thenAnswer((_) async {}); logRepo = MockWorkoutLogRepository(); when(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); @@ -232,6 +233,8 @@ void main() { verify(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1); expect(gymState.state.currentPage, rest + 2); + // Only once the notification shows the new rest may iOS suspend the app + verifyInOrder([service.showControls(any, any), service.actionHandled()]); final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; expect((alarms.last as RestAlarm).payload.restSlotUuid, slotPage(rest + 2).uuid); }); @@ -284,7 +287,7 @@ void main() { .handleAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, null); await settle(); - verify(service.showNotLogged(any)).called(1); + verifyInOrder([service.showNotLogged(any), service.actionHandled()]); verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); }); diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index ba7369fa4..6eeb9542a 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -123,6 +123,15 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } /// A class which mocks [WorkoutLogRepository]. diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart index 5eb31deec..6318b0929 100644 --- a/test/features/routines/notifications/workout_notification_service_test.dart +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -46,6 +47,37 @@ void main() { setUpAll(tzdata.initializeTimeZones); + group('actionHandled', () { + const tasksChannel = MethodChannel('de.wger.flutter/notification_actions'); + late List taskCalls; + + setUp(() { + taskCalls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(tasksChannel, (call) async { + taskCalls.add(call.method); + return null; + }); + addTearDown( + () => binding.defaultBinaryMessenger.setMockMethodCallHandler(tasksChannel, null), + ); + }); + + test('Ends the background task on iOS', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + + await LocalWorkoutNotificationService().actionHandled(); + + expect(taskCalls, ['actionHandled']); + }); + + test('Does nothing on Android, which keeps no task', () async { + await LocalWorkoutNotificationService().actionHandled(); + + expect(taskCalls, isEmpty); + }); + }); + setUp(() { // The Android side of the plugin, talking to a fake platform channel FlutterLocalNotificationsPlatform.instance = AndroidFlutterLocalNotificationsPlugin(); diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index ba8bbf2db..4fda3ae2c 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -715,4 +715,13 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); + + @override + _i10.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); } diff --git a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart index 3b91bfbcd..6bd72f272 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart @@ -121,4 +121,13 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); }