Skip to content

geolocator_apple > 2.2.2 does not work in background ? #1270

New issue

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

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

Already on GitHub? # to your account

Closed
ChristopheLyonnaz opened this issue Jun 7, 2023 · 10 comments
Closed

geolocator_apple > 2.2.2 does not work in background ? #1270

ChristopheLyonnaz opened this issue Jun 7, 2023 · 10 comments
Labels
platform: ios Issue is related to the iOS platform

Comments

@ChristopheLyonnaz
Copy link

💬 Questions and Help

Hello,
I have a flutter application using geolocator 9.0.2 on iOS.
My application is designed to run continuously for a long time in order to report user position, although the application is in background (smartphone in sleep mode or application not on the front).
Using geolocator_apple 2.2.2,everything is OK, but using 2.2.5 or 2.2.6, I get an error message :

LOCATION UPDATE FAILURE:Error reason: (null)Error description: The operation couldn’t be completed. (kCLErrorDomain error 1.)
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: The operation couldn’t be completed. (kCLErrorDomain error 1.)
#0      GeolocatorApple.getPositionStream.<anonymous closure> (package:geolocator_apple/src/geolocator_apple.dart:188:9)
#1      Stream.handleError.<anonymous closure> (dart:async/stream.dart:929:16)
#2      _HandleErrorStream._handleError (dart:async/stream_pipe.dart:269:17)
#3      _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:157:13)
#4      _RootZone.runBinaryGuarded (dart:async/zone.dart:1605:10)
#5      _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
#6      _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:7)
#7      _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:280:7)

And my application is no longer collecting the location.

I've checked all permissions are active (Location: While Using the App, and Background : location capability is set).
Any idea why I keep having this issue ?

Thank you for your help
Regards,
Christophe.

@Dev-Paccore
Copy link

+1

@TimHoogstrate
Copy link
Contributor

Does it stop collecting the location data immediately or after some time, and can you inform me about how long it takes before you run into this issue?

It would be helpful if you could provide the output of 'flutter doctor -v' and clear, step-by-step instructions to reproduce the issue in the comment section. This will assist us in better understanding and addressing the problem.

@ChristopheLyonnaz
Copy link
Author

ChristopheLyonnaz commented Jun 13, 2023

Hi Tim,

I give you a quick feedback with the information I can have right now.
It stops about 30s after I toggle to another application. Probably when iOS decides its time to save battery.

To reproduce

Build an application that continuously retrieve location every 30s for instance.
My pubspec.yaml contains:

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  ../..
  geolocator: ^9.0.2                     # Calcul de coordonnes GPS
  ../..
  wakelock : ^0.6.2                      # pour interdire la mise en veille automatique
  ../..

Here is my pseudo-code (I'll try and give you a real test program to investigate):

    await Geolocator.isLocationServiceEnabled();
    permission = await Geolocator.checkPermission();
    positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen((Position position) {
        _position = position;
      print(" GPS : " + _position.latitude.toString() + " / " + _position.longitude.toString());
    });

When I put my application in background (i.e I switch to another application, or I switch off my smartphone screen to sleep), after 30s, my application is sending the error message as given previously.

As soon as I add the 2 following lines, it works fine.

dependency_overrides:
  geolocator_apple: 2.2.2              

flutter doctor outputs:

[✓] Flutter (Channel stable, 3.7.10, on macOS 12.3.1 21E258 darwin-arm64, locale en-FR)
• Flutter version 3.7.10 on channel stable at /Users/christophelyonnaz/DEVTOOLS/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 4b12645012 (2 months ago), 2023-04-03 17:46:48 -0700
• Engine revision ec975089ac
• Dart version 2.19.6
• DevTools version 2.20.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at /Users/christophelyonnaz/Library/Android/sdk
• Platform android-30, build-tools 30.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 13F17a
• CocoaPods version 1.11.3

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

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

[✓] VS Code (version 1.60.2)
• VS Code at /Users/christophelyonnaz/Downloads/Visual Studio Code.app/Contents
• Flutter extension can be installed from:
🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (2 available)
• macOS (desktop) • macos • darwin-arm64 • macOS 12.3.1 21E258 darwin-arm64
• Chrome (web) • chrome • web-javascript • Google Chrome 114.0.5735.106

[✓] HTTP Host Availability
• All required HTTP hosts are available

• No issues found!

@mvanbeusekom
Copy link
Member

Hi @ChristopheLyonnaz,

Thank you for providing the additional details, we will start looking into this. If you do manage to create a real testing application that would still help out a lot.

@TimHoogstrate
Copy link
Contributor

TimHoogstrate commented Jun 26, 2023

Hi @ChristopheLyonnaz,

Can you please confirm the following: Do you have allowBackgroundLocationUpdates set to true in your locationSettings? e.g. like below (see example app):

geolocatorApple.getPositionStream(
          locationSettings: AppleSettings(
        accuracy: LocationAccuracy.best,
        distanceFilter: 10,
        activityType: ActivityType.other,
        // Only set showBackgroundLocationIndicator and
        // allowBackgroundLocationUpdates to true if our app will be started up
        // in the background.
        showBackgroundLocationIndicator: false,
        **allowBackgroundLocationUpdates: true,**
      ));

And:

  /// For this setting to work Info.plist should contain the following keys:
  /// - UIBackgroundModes and the value should contain "location"
  /// - NSLocationAlwaysUsageDescription

Waiting for your reply,

Tim

@TimHoogstrate TimHoogstrate added status: needs more info We need more information before we can continue work on this issue. platform: ios Issue is related to the iOS platform labels Jun 26, 2023
@ChristopheLyonnaz
Copy link
Author

Hi @TimHoogstrate ,

Great news, this option totally fixes my issue. I am so sorry not being able to see it earlier.
Thank you for your valuable help.

Christophe.

@github-actions github-actions bot removed the status: needs more info We need more information before we can continue work on this issue. label Jul 4, 2023
@Chantha123
Copy link

[✓] Flutter (Channel stable, 3.16.5, on macOS 14.2.1 23C71 darwin-arm64, locale en-KH)
• Flutter version 3.16.5 on channel stable at /Users/kungchantha/Developer/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 78666c8dc5 (4 weeks ago), 2023-12-19 16:14:14 -0800
• Engine revision 3f3e560236
• Dart version 3.2.3
• DevTools version 2.28.4

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.2)
• Android SDK at /Users/kungchantha/Library/Android/sdk
• Platform android-33, build-tools 33.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 15C500b
• CocoaPods version 1.14.3

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

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

[✓] VS Code (version 1.76.0)
• VS Code at /Users/kungchantha/Downloads/Visual Studio Code.app/Contents
• Flutter extension version 3.80.0

This is my flutter doctor -v . I got the same issue with ios how can fix I already do it step by step but Geolocation still return the permission is denied .

@ChristopheLyonnaz
Copy link
Author

Hi Chantha,

This issue was raised quite a long time ago.
Since this, I slighty changed my code. The following simplified code is what I implemented on iOS :

  void requestLocationUpdates() async {
    LocationSettings locationSettings;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    permission = await Geolocator.checkPermission();

      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.airborne,
        distanceFilter: 50,
        pauseLocationUpdatesAutomatically: true,
        // Only set to true if our app will be started up in the background.
        showBackgroundLocationIndicator: true,
        allowBackgroundLocationUpdates: true,
      );

    positionStream = Geolocator.getPositionStream(locationSettings: locationSettings) // 2 mètres entre 2 positions
        .listen((Position position) {
      _position = position;
}

@Chantha123
Copy link

Hi Chantha,

This issue was raised quite a long time ago. Since this, I slighty changed my code. The following simplified code is what I implemented on iOS :

  void requestLocationUpdates() async {
    LocationSettings locationSettings;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    permission = await Geolocator.checkPermission();

      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.airborne,
        distanceFilter: 50,
        pauseLocationUpdatesAutomatically: true,
        // Only set to true if our app will be started up in the background.
        showBackgroundLocationIndicator: true,
        allowBackgroundLocationUpdates: true,
      );

    positionStream = Geolocator.getPositionStream(locationSettings: locationSettings) // 2 mètres entre 2 positions
        .listen((Position position) {
      _position = position;
}

Yes Thanks brother. I already apply this but it doesn't work . I still got error :
Unhandled Exception: The operation couldn’t be completed. (kCLErrorDomain error 1.)
#0 GeolocatorApple.getPositionStream. (package:geolocator_apple/src/geolocator_apple.dart:188:9)
#1 Stream.handleError. (dart:async/stream.dart:923:16)
#2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:269:17)
#3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:157:13)
#4 _RootZone.runBinaryGuarded (dart:async/zone.dart:1606:10)
#5 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
#6 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:7)
#7 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:280:7)
#8 _ForwardingStreamSubscription._addError (dart:async/stream_pipe.dart:128:11)
#9 _ForwardingStream._handleError (dart:async/stream_pipe.dart:95:10)
#10 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:157:13)
#11 _RootZone.runBinaryGuarded (dart:async/zone.dart:1606:10)
#12 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
#13 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:7)
#14 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:280:7)
#15 _SyncBroadcastStreamController._sendError. (dart:async/broadcast_stream_controller.dart:392:20)
#16 _BroadcastStreamController._forEachListener (dart:async/broadcast_stream_controller.dart:322:15)
#17 _SyncBroadcastStreamController._sendError (dart:async/broadcast_stream_controller.dart:391:5)
#18 _AsBroadcastStreamController.addError (dart:async/broadcast_stream_controller.dart:486:5)
#19 _RootZone.runBinaryGuarded (dart:async/zone.dart:1606:10)
#20 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
#21 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:7)
#22 _DelayedError.perform (dart:async/stream_impl.dart:526:14)
#23 _PendingEvents.handleNext (dart:async/stream_impl.dart:620:11)
#24 _PendingEvents.schedule. (dart:async/stream_impl.dart:591:7)
#25 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#26 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

@ChristopheLyonnaz
Copy link
Author

ChristopheLyonnaz commented Jan 16, 2024

Just to be sure, now I've migrated to the following content in pubspec.yaml:

  sdk: '>=3.1.0 <4.0.0' # Dart SDK release
  geolocator: ^10.0.1 # which leads to geolocator_apple-2.3.2.

At the time I fixed workaround the issue, I had:

  sdk: ">=2.7.0 <3.0.0"

  geolocator: ^9.0.2                 

dependency_overrides:
  geolocator_apple: 2.2.2                

And obviously, I have the following in my Info.plist:

	<key>NSLocationAlwaysUsageDescription</key>
	<string>This app needs access to location xxxx.</string>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>This app needs access to location xxxx.</string>
	<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
	<string>This app needs access to location xxxx.</string>

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
platform: ios Issue is related to the iOS platform
Projects
None yet
Development

No branches or pull requests

5 participants