Baseflow / flutter-geolocator

Android and iOS Geolocation plugin for Flutter
https://baseflow.com/
MIT License
1.24k stars 645 forks source link

[Bug]: LOCATION UPDATE FAILURE:Error reason: (null)Error description: The operation couldn’t be completed. (kCLErrorDomain error 1.) #1555

Open alladyaditi opened 4 weeks ago

alladyaditi commented 4 weeks ago

Please check the following before submitting a new issue.

Please select affected platform(s)

Steps to reproduce

Steps to reproduce

  1. Setup the Flutter app: Integrate the Geolocator package into a Flutter project.
  2. Request location permissions: Include the necessary permissions (NSLocationWhenInUseUsageDescription, NSLocationAlwaysUsageDescription, etc.) in the Info.plist file.
  3. Invoke Geolocator: Attempt to retrieve the current location using Geolocator.getCurrentPosition() or listen to location updates using Geolocator.getPositionStream().
  4. Run the app on an iOS device: Deploy the app to an iOS device (not an emulator) and monitor the logs for any errors.

Expected results

The app should request location permissions if not already granted, and then successfully retrieve the current location of the device, either once via getCurrentPosition() or continuously via getPositionStream().

Actual results

Unhandled Exception: The operation couldn’t be completed. (kCLErrorDomain error 1.)

Code sample

This is the logic i used in my code?

Future<void> _requestLocationPermission() async {
  if (_isRequestingPermission) return;

  _isRequestingPermission = true;
  try {
    var status = await Permission.locationWhenInUse.request();
    if (status.isGranted) {
      _loadInitialLocation();
    } else {
      // Handle permission denial
    }
  } finally {
    _isRequestingPermission = false;
  }
}

  // Future<void> _requestLocationPermission() async {
  //   var status = await Permission.locationWhenInUse.request();
  //   if (status.isGranted) {
  //     _loadInitialLocation();
  //   } else {
  //     // Handle permission denial
  //   }
  // }

  Future<void> _getCurrentLocation() async {
    _currentPosition = await geolocator.Geolocator.getCurrentPosition(locationSettings: const geolocator.LocationSettings(accuracy: geolocator.LocationAccuracy.high));
    if (!mounted) return;

    //_initialCameraOptions = _getCameraOptions(_currentPosition);
    _mapboxMap.flyTo(_getCameraOptions(_currentPosition), MapAnimationOptions(duration: 1000));
    _updateLocationPuck();
  }

  void _enableLocationUpdates() {
    geolocator.Geolocator.getPositionStream(
        locationSettings: const geolocator.LocationSettings(accuracy: geolocator.LocationAccuracy.high)
    ).listen((geolocator.Position position) {
      if (!mounted) return;

      setState(() {
        _currentPosition = position;
        _updateLocationPuck();
      });
    });
  }

Screenshots or video

LOCATION UPDATE FAILURE:Error reason: (null)Error description: The operation couldn’t be completed. (kCLErrorDomain error 1.)
[ERROR:flutter/runtime/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:931: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:384:15)
#6      _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:402:7)
#7      _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:306: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:384:15)
#13     _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:402:7)
#14     _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:306:7)
#15     _SyncBroadcastStreamController._sendError.<anonymous closure> (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:384:15)
#21     _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:402:7)
#22     _DelayedError.perform (dart:async/stream_impl.dart:552:14)
#23     _PendingEvents.handleNext (dart:async/stream_impl.dart:646:11)
#24     _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:617:7)
#25     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#26     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

Version

13.0.1

Flutter Doctor output

[✓] Flutter (Channel stable, 3.22.2, on macOS 14.5 23F79 darwin-x64, locale en-US) • Flutter version 3.22.2 on channel stable at /Users/aditiallady/devlopment/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 761747bfc5 (2 months ago), 2024-06-05 22:15:13 +0200 • Engine revision edd8546116 • Dart version 3.4.3 • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) • Android SDK at /Users/aditiallady/Library/Android/sdk • Platform android-34, build-tools 34.0.0 • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11572160) • All Android licenses accepted.

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

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

[✓] Android Studio (version 2023.3) • 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 17.0.10+0-17.0.10b1087.21-11572160)

[✓] VS Code (version 1.92.0) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.94.0

[✓] Connected device (5 available) • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64 • Android 14 (API 34) (emulator) • Aditi’s iPhone (mobile) • 00008130-000E21A004298D3A • ios • iOS 17.5.1 21F90 • iPhone 15 Pro Max (mobile) • 1F14C548-F714-4573-8B73-4DA1E72B59A1 • ios • com.apple.CoreSimulator.SimRuntime.iOS-17-5 (simulator) • macOS (desktop) • macos • darwin-x64 • macOS 14.5 23F79 darwin-x64 • Chrome (web) • chrome • web-javascript • Google Chrome 127.0.6533.101

[✓] Network resources • All expected network resources are available.

• No issues found!

TimHoogstrate commented 3 weeks ago

Dear @alladyaditi,

Thanks for your input. kCLErrorDomain Code 1 occurs when the user has denied your app access to location services. Can you check if the location services are enabled in : Settings > Privacy > Location Services > Your App.

Kind regards,

alladyaditi commented 3 weeks ago

They are enabled, location is enabled

alladyaditi commented 3 weeks ago

the location is only shown when the location is used on while using the app but not ask the next time or when I share

alladyaditi commented 3 weeks ago

the location shows once on the while using the app and then when I leave the page and comeback the user location button does not work and returns the error above

TimHoogstrate commented 3 weeks ago

Dear @alladyaditi,

The situation you describe seems like a different issue. The original issue seems to be resolved. Please file a new issue with clear steps to reproduce.

Kind regards

alladyaditi commented 3 weeks ago

i am still getting the issue

alladyaditi commented 3 weeks ago

flutter/runtime/dart_vm_initializer.cc(41)] 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:931: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:384:15)

6 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:402:7)

7 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:306:7)

8 _ForwardingStreamSubscription._addError (dart:async/stream_pipe.dart:128:11)

9 _ForwardingStream._handleError (dart:async/stream_pipe.dart:95:10)

10 _ForwardingStream<…>

TimHoogstrate commented 3 weeks ago

Do you get the same issue with the example app?

Kind regards,

alladyaditi commented 3 weeks ago

Yes

Get Outlook for iOShttps://aka.ms/o0ukef


From: TimHoogstrate @.> Sent: Wednesday, August 21, 2024 7:21:52 AM To: Baseflow/flutter-geolocator @.> Cc: alladyaditi @.>; Mention @.> Subject: Re: [Baseflow/flutter-geolocator] [Bug]: LOCATION UPDATE FAILURE:Error reason: (null)Error description: The operation couldn’t be completed. (kCLErrorDomain error 1.) (Issue #1555)

Do you get the same issue with the example app?

Kind regards,

— Reply to this email directly, view it on GitHubhttps://github.com/Baseflow/flutter-geolocator/issues/1555#issuecomment-2301810695, or unsubscribehttps://github.com/notifications/unsubscribe-auth/APWSFH7AZIW7RG5TVWZURYTZSRZ5BAVCNFSM6AAAAABMQSA6G6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGMBRHAYTANRZGU. You are receiving this because you were mentioned.Message ID: @.***>

tuyen3962 commented 2 weeks ago

I also face with this issue. When I use getPositionStream to handle the foreground task, it work normally in the several times, but it throw error "The operation couldn’t be completed. (kCLErrorDomain error 1.)" after 1 minutes.

Library version: geolocator: ^12.0.0 flutter_foreground_task: ^8.0.0 mapbox_maps_flutter: ^2.1.0

Flutter 3.22.3

But I have granted the location permission as while in use. Location service also enable.

When I run it in the foreground task. I setup the following setting in ios: locationSettings = AppleSettings( accuracy: LocationAccuracy.bestForNavigation, activityType: ActivityType.fitness, distanceFilter: DISTANCE_UPDATE.toInt(), showBackgroundLocationIndicator: true, allowBackgroundLocationUpdates: true, );

However, when I set the always for location permission, it work correctly. So can you check it in the case of while in use because android work normally in this case.

Thank you.

alladyaditi commented 2 weeks ago

Hi i am using workmanger but still i am still getting the same issues

alladyaditi commented 2 weeks ago

plese tell me what to do ?

tuyen3962 commented 2 weeks ago

I have fix this issue. It is not relevant the logic but It require some minor config which does not mention in this docs. But let me share with you guys to try. Because I can not find any solution about this issue in the flutter and iOS side, I switch to research in the React Native which handle the background location. You can follow this documents to setup two things: Privacy plist and one BGTaskSchedulerPermittedIdentifiers in your info.plist

The link: https://github.com/Rapsssito/react-native-background-actions/blob/master/INSTALL.md

Hope this you guys and if this resolve your issue, please host update the document for further using

alladyaditi commented 2 weeks ago

Thanks, I'll check it out.

On Tue, Aug 27, 2024 at 10:38 PM tuyen3962 @.***> wrote:

I have fix this issue. It is not relevant the logic but It require some minor config which does not mention in this docs. But let me share with you guys to try. Because I can not find any solution about this issue in the flutter and iOS side, I switch to research in the React Native which handle the background location. You can follow this documents to setup two things: Privacy plist and one BGTaskSchedulerPermittedIdentifiers in your info.plist

The link: https://github.com/Rapsssito/react-native-background-actions/blob/master/INSTALL.md

Hope this you guys and if this resolve your issue, please host update the document for further using

— Reply to this email directly, view it on GitHub https://github.com/Baseflow/flutter-geolocator/issues/1555#issuecomment-2313983423, or unsubscribe https://github.com/notifications/unsubscribe-auth/APWSFHZAVG2Q2MXS4SPNLSTZTUZZVAVCNFSM6AAAAABMQSA6G6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGMJTHE4DGNBSGM . You are receiving this because you were mentioned.Message ID: @.***>

alladyaditi commented 2 weeks ago

this is not work as well

tuyen3962 commented 1 week ago

huh, Are you using the getCurrentPosition function to update your location in the background? In the background or foreground service task, I use the getPositionStream function and it work for me.

Sample code: _locationSub = myLocationService .listenChangeOfPosition(isBackground: true) .listen((position) => onHandleNewPosition(position));

Stream listenChangeOfPosition({bool isBackground = false}) { late LocationSettings locationSettings;

if (defaultTargetPlatform == TargetPlatform.android) {
  locationSettings = AndroidSettings(
    accuracy: LocationAccuracy.bestForNavigation,
    distanceFilter: DISTANCE_UPDATE.toInt(),
    forceLocationManager: true,
    intervalDuration: const Duration(seconds: 1),
  );
} else if (defaultTargetPlatform == TargetPlatform.iOS ||
    defaultTargetPlatform == TargetPlatform.macOS) {
  locationSettings = AppleSettings(
    accuracy: LocationAccuracy.bestForNavigation,
    activityType: ActivityType.fitness,
    distanceFilter: DISTANCE_UPDATE.toInt(),
    showBackgroundLocationIndicator: isBackground,
    allowBackgroundLocationUpdates: true,
  );
} else {
  locationSettings = LocationSettings(
    accuracy: LocationAccuracy.bestForNavigation,
    distanceFilter: DISTANCE_UPDATE.toInt(),
  );
}

return Geolocator.getPositionStream(locationSettings: locationSettings);

}

alladyaditi commented 1 week ago

Future _getCurrentLocation() async { _currentPosition = await geolocator.Geolocator.getCurrentPosition( locationSettings: const geolocator.LocationSettings( accuracy: geolocator.LocationAccuracy.high)); if (!mounted) return;

//_initialCameraOptions = _getCameraOptions(_currentPosition);
_mapboxMap.flyTo(_getCameraOptions(_currentPosition),
    MapAnimationOptions(duration: 1000));
_updateLocationPuck();

}

void _enableLocationUpdates() { geolocator.Geolocator.getPositionStream( locationSettings: const geolocator.LocationSettings( accuracy: geolocator.LocationAccuracy.high)) .listen((geolocator.Position position) { if (!mounted) return;

setState(() {
  _currentPosition = position;
  _updateLocationPuck();
});

}); } this is my code

mcorbelli commented 1 week ago

the problem still exists. i created a simple app to retrieve the location via a button. very simple. the logic to retrieve the coordinates i took directly from the description of the geolocator package (and it is correct). looking carefully at the logs, the coordinates are correctly retrieved by the function, but then it breaks down and the exception LOCATION UPDATE FAILURE:Error reason: (null)Error description: The operation couldn't be completed. (kCLErrorDomain error 0.).

so the location is correctly retrieved, but it goes no further.

carbon

alladyaditi commented 1 week ago

That's weird. So it is a geolocater issue?

On Mon, Sep 2, 2024 at 2:15 PM Mattia Corbelli @.***> wrote:

the problem still exists. i created a simple app to retrieve the location via a button. very simple. the logic to retrieve the coordinates i took directly from the description of the geolocator package (and it is correct). looking carefully at the logs, the coordinates are correctly retrieved by the function, but then it breaks down and the exception LOCATION UPDATE FAILURE:Error reason: (null)Error description: The operation couldn't be completed. (kCLErrorDomain error 0.).

so the location is correctly retrieved, but it goes no further.

carbon.png (view on web) https://github.com/user-attachments/assets/c94f113d-ebd1-4b83-b320-9e994f59992e

— Reply to this email directly, view it on GitHub https://github.com/Baseflow/flutter-geolocator/issues/1555#issuecomment-2325172231, or unsubscribe https://github.com/notifications/unsubscribe-auth/APWSFH55734ZSCY5334EWVDZUSTLZAVCNFSM6AAAAABMQSA6G6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGMRVGE3TEMRTGE . You are receiving this because you were mentioned.Message ID: @.***>

tuyen3962 commented 1 week ago

https://github.com/Rapsssito/react-native-background-actions/blob/master/INSTALL.md Do you follow this document to update the config in your info.plist?

If you want to run it in the foreground or background task, you have to turn on the location and the background config and force user to turn on the location service in their device.

And in the podfile, You have to remove the following line:

if target.name == "geolocator_apple"

#   target.build_configurations.each do |config|
#     config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'BYPASS_PERMISSION_LOCATION_ALWAYS=1']
#   end
# end
alladyaditi commented 1 week ago

if target.name == "geolocator_apple"

target.build_configurations.each do |config|

config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'BYPASS_PERMISSION_LOCATION_ALWAYS=1']

end

end

i dont have that in my podfile

alladyaditi commented 1 week ago

target 'Runner' do use_frameworks! use_modular_headers!

flutter_install_all_ios_pods File.dirname(File.realpath(FILE)) target 'RunnerTests' do inherit! :search_paths end end

post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) end end

alladyaditi commented 1 week ago

this is what is in my podfile

alladyaditi commented 1 week ago
NSLocationWhenInUseUsageDescription
<string>Shows your location on the map and helps improve the map</string>
<key>io.flutter.embedded_views_preview</key> this is what is in my info.plist file