Skip to content

[Bug]: Requesting locationAlways does not await user's response. #1152

Open

Description

@jeffscaturro-aka

Please check the following before submitting a new issue.

Please select affected platform(s)

  • Android
  • iOS
  • Windows

Steps to reproduce

  1. Check result of requesting locationWhenInUse permissions await Permission.locationWhenInUse.request().
  2. Check result of requesting locationAlways permissions await Permission.locationAlways.request().

Expected results

We expect the both requests to properly await the user's response to the iOS system dialog, and returns the user's choice.

Actual results

In the above steps, the first request properly awaits the user's response to the iOS system dialog, and returns the user's choice.

The second request immediately returns a response of not granted because the user hasn't responded yet to the dialog.

Code sample

  Future<bool> _requestLocationWhileInUse() async {
    // This actually waits for user to respond to dialog prompt before
    // continuing to return the status.isGranted.
    final status = await Permission.locationWhenInUse.request();

    return status.isGranted;
  }

  Future<bool> _requestLocationAlways() async {
    // This does not wait for user to respond to dialog prompt before
    // continuing to return the status.isGranted, thus, we often receive
    // false here, and have to check after the user responds to the dialog.
    final status = await Permission.locationAlways.request();

    return status.isGranted;
  }

Screenshots or video

Screenshots or video demonstration

[Upload media here]

Version

10.4.3 - 11.0.0

Flutter Doctor output

Doctor output
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.13.0, on macOS 13.5.1 22G90 darwin-arm64, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 14.3.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] VS Code (version 1.81.1)
[✓] Connected device (5 available)
[✓] Network resources

• No issues found!

Activity

  1. jeffscaturro-aka commented on Sep 13, 2023

    @jeffscaturro-aka
    Author

    Looks like a similar issue was previously filed around this, but marked as resolved: #1086 (=> https://github.com/Baseflow/flutter-permission-handler/pull/1089/files#r1254302197).

  2. added
    platform: ios
    type: bug
    P2
    on Sep 14, 2023
  3. niksen75 commented on Sep 18, 2023

    @niksen75

    Same issue.

    iOS 16.6.1, physical device

    Pubspec.yaml
    permission_handler: ^10.4.5
    permission_handler_apple: ^9.1.4

    Podfile
    config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
    '$(inherited)',
    ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
    'PERMISSION_LOCATION=1',
    ]

  4. self-assigned this
    on Sep 20, 2023
  5. added
    refactor
    on Sep 20, 2023
  6. mvanbeusekom commented on Sep 21, 2023

    @mvanbeusekom
    Member

    Hi @jeffscaturro-aka, @niksen75,

    Thank you for reporting this issue and providing detailed descriptions. I was able to reproduce the problem and did more detailed investigation.

    Unfortunately the issue is not really easy to solve in our current architecture where we simply await the future when requesting permissions. The reason is that iOS will not always provide a status update when requesting "Always allow" permissions. Here are the situations:

    User selected "Allow once"

    When requesting location permissions and the user initially selected "Only once", requesting locationAlways will not trigger the permission dialog at all and no result is provided. Unfortunately Apple doesn't provide an API which informs us the user initially selected "Only once", instead the "When in use" permission is returned. This is also explained in Apple's documentation.

    User selected "When in use" and follows up with "Keep When in use"

    When the user selected "When in use" at the moment we initially request location permissions Apple will return the "When in use" permission. Now if the app requests location always permission the following happens:

    • iOS will immediately call the locationManager:didChangeAuthorizationStatus: callback with the kCLAuthorizationStatusAuthorizedWhenInUse status (this happens before the second permission dialog is shown).
    • Next iOS will show the permission dialog asking the user to "Keep using While in Use" or "Change to Allow Always".
    • If the user selects "Keep using While in Use" iOS will close the dialog but will not inform us of any status updates.

    User selected "When in use" and follows up with "Change to Allow always"

    Again the user initially provided "When in use" permissions and the app is requesting location always permission:

    • Before the second dialog is shown iOS will call the locationManager:didChangeAuthorizationStatus: callback and confirms the current permission reporting the kCLAuthorizationStatusAuthorizedWhenInUse status.
    • iOS will show the permission dialog asking the user to "Keep using While in Use" or "Change to Allow Always".
    • Only if the user select "Change to Allow Always", iOS will call the locationManager:didChangeAuthorizationStatus: method and inform us of the new kCLAuthorizationStatusAuthorizedAlways status.

    As you can see this makes it really hard (not to say impossible) to reliably await for the correct status when requesting location alway permission. This due to the fact that in several situations iOS will simply not inform us about the status when the user makes a selection.

    We understand that the current solution provided by the plugin is not really helpful and therefore we are planning to do a refactor of the plugin where we will provide developers with the option to listen to a stream providing permission status changes instead of enforcing developers to await the request method for a status update. We will start the refactor very soon and hopefully can provide updates in the coming months. Until this time, we are not really able to provide a more solid solution and we hope you all understand.

    We will keep this issue open to help track the refactor process and ensure this issue will be resolved as part of the refactor process.

    P.S. alternative ideas are of course welcome.

  7. jeffscaturro-aka commented on Oct 6, 2023

    @jeffscaturro-aka
    Author

    @mvanbeusekom thank you so much for the triage and in depth explanation here, it is much appreciated and gives a great understanding of the limitations we're facing. I feel most developers can understand Apple doesn't always make it easy on us, especially when factoring in user privacy and permissions (rightfully so).

    A workaround we had in place was simply utilizing a WidgetsBindingObserver where we were asking for this permission and listening to its lifecycle state changes (didChangeAppLifecycleState). I hope that helps some others who stumble across this issue, and of course, other ways around this would be welcomed to include on this thread!

  8. Biowulf21 commented on Feb 21, 2024

    @Biowulf21

    For anyone reading this in the future, this is the didChangeAppLifecycleState workaround that people are mentioning:

    class _LocationPageState extends State<LocationPage>
        with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      // this is used to listen to the app lifecycle state
      // this function is called affter the OS location permission popup appears because
      // the app is considered "paused" when that happens and "resumed" after the user
      // has selected an option
      @override
      Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
        super.didChangeAppLifecycleState(state);
        if (state == AppLifecycleState.resumed && Platform.isIOS) {
          print('resumed ios');
          await handleIOSLocationWorkAround(context, bloc);
        }
      }
    
  9. nayanaubie commented on Mar 22, 2024

    @nayanaubie

    @Biowulf21 What is the exact workaround and what will your method handleIOSLocationWorkAround do?
    I am just wondering as there is no connection between AppLifecycleState and this issue.

  10. Biowulf21 commented on Mar 22, 2024

    @Biowulf21

    @Biowulf21 What is the exact workaround and what will your method handleIOSLocationWorkAround do? I am just wondering as there is no connection between AppLifecycleState and this issue.

    The app goes to suspend state when the location permission pop up appears and goes to resumed state when it's closed.

  11. iJack93 commented on Nov 12, 2024

    @iJack93

    Hi @mvanbeusekom,
    Is there any news about this permission status stream implementation that you've mentioned above?

    Thank you very much!

  12. alle-iacob commented on Oct 26, 2026

    @alle-iacob

    Hi. Is there a timeline scheduled for this fix?

  13. khb-works commented on Oct 28, 2026

    @khb-works
    Contributor

    I fixed the locationAlways status in #1577 and looked into this one (and #1457) next. I used the apple example on an iOS 26.5 simulator with current main (0ea2555, permission_handler_apple 9.6.4), and logged when request() returns and when the app lifecycle changes.

    Steps request() returned Notes
    When In Use granted, request locationAlways, tap "Change to Always Allow" denied after 9 ms The prompt appeared 173 ms after the request. The status afterwards is granted.
    Same, tap "Keep Only While Using" denied after 15 ms The prompt appeared 317 ms after the request. The status afterwards is permanentlyDenied, and a second request returns permanentlyDenied right away.
    "Allow Once", then request locationAlways denied after 9 ms No prompt, as expected.
    Request locationWhenInUse, lock the screen while the prompt is showing never returns Locking dismisses the prompt, and the app is active for a moment before it goes to the background. The next request fails with ERROR_ALREADY_REQUESTING_PERMISSIONS (#1035, #1261).

    The first two rows come from the callback you described in 2023. Right after requestAlwaysAuthorization, the delegate reports the current When In Use status, and the strategy answers the request with denied in locationManager:didChangeAuthorizationStatus:. It already observes UIApplicationDidBecomeActiveNotification for Always requests, but by the time that fires, the request has already been answered. In the last row nothing answers the request, so _methodResult in PermissionHandlerPlugin is never cleared.

    The third row is why that callback can't just be ignored. After Allow Once, Core Location "ignores further calls to requestAlwaysAuthorization() due to the temporary authorization", so that callback is the only thing that comes back.

    As an alternative to the stream refactor, I'd like to end location requests based on the app lifecycle:

    • A location prompt makes the app resign active. When the app becomes active again, read the authorization status and return it. This covers both choices in the upgrade prompt and a prompt dismissed by locking the screen.
    • Ignore a delegate callback that only repeats the status from before the request.
    • If the app doesn't resign active within 2 seconds of the request (no prompt, as after Allow Once), return the current status. This is the only part that depends on timing. In my runs every prompt appeared within 0.6 seconds.
    • Mark Always as asked only when its prompt actually appeared. Today the flag is set as soon as requestAlwaysAuthorization is called, so after Allow Once, later Always requests would return permanentlyDenied without asking.

    I tried this in a prototype on the same simulator:

    • "Change to Always Allow" returns granted and "Keep Only While Using" returns permanentlyDenied, when the user picks them.
    • After Allow Once, the Always request returns denied after the 2 second wait. After restarting the app, which ends the temporary authorization, and granting When In Use, the Always request showed the upgrade prompt.
    • Locking the screen ends the request with denied, and the next request shows the prompt again.
    • Requesting location together with camera, in either order, didn't end the location request early. Going home and opening Notification Center are blocked while the prompt is up, so locking the screen is the only way to leave it without answering.

    Downsides I know of:

    • If a prompt appears more than 2 seconds after the request (a slow device, or a busy main thread at launch), the request is answered before the user picks. The status read afterwards is still right. I only measured on the simulator.
    • The timeout also covers When In Use requests, which today wait for the delegate. Leaving it out there avoids the early answer above, but then a request that shows no prompt would never return.
    • After Allow Once, the Always request takes 2 seconds to return, and each further Always request in that session would also wait 2 seconds and return denied, since Core Location ignores it.
    • It relies on the app staying inactive between consecutive prompts, as it did here. If an iOS version makes the app active in between, a location request whose status doesn't change (Keep Only While Using, or a dismissed prompt) could be answered when another permission's prompt closes.
    • Anything else that makes the app resign active right after the request, like an incoming call, is taken as the prompt, so the request can end before the real prompt is answered.
    • I only tested on the iOS 26.5 simulator. The prototype drops the current handling of a second notDetermined callback, which older iOS versions might rely on.

    This stays inside LocationPermissionStrategy and doesn't change the API. In the PR I'd add XCTests with an injected CLLocationManager.

    #1511 handles the lock screen case for all permissions by failing the pending request with REQUEST_INTERRUPTED when the app goes to the background. For location, this approach returns the actual status instead of an error.

    Would you take a PR along these lines?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2platform: iosrefactortype: bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions