mauron85 / react-native-background-geolocation

Background and foreground geolocation plugin for React Native. Tracks user when app is running in background.
Apache License 2.0
1.33k stars 561 forks source link

the app crashes when the library is initialized. IOS #513

Closed Yrsafam closed 3 years ago

Yrsafam commented 3 years ago

Your Environment

Context

when you try to initialize the library on ios, the app crashes. I apply the Call stack from XCode. I would be grateful for at least a hint in which direction to look. The problem is only on ios. Works on android.

`import React, {Component} from 'react';
import {Alert} from 'react-native';
import BackgroundGeolocation from '@mauron85/react-native-background-geolocation';
import {API_ADDRESS, API_DOMEN} from '../../constants';
import CookieManager from '@react-native-community/cookies';

const FREQUENCY_HIGH = 60000;
class BgTracking extends Component {
  async componentDidMount() {
    let cookie = await CookieManager.get(API_DOMEN);
    BackgroundGeolocation.configure({
      desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
      stationaryRadius: 15,
      distanceFilter: 5,
      notificationTitle: this.props.title,
      notificationText: this.props.text,
      debug: false,
      startOnBoot: true,
      locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
      interval: FREQUENCY_HIGH,
      fastestInterval: FREQUENCY_HIGH,
      activitiesInterval: FREQUENCY_HIGH,
      stopOnStillActivity: false,
      stopOnTerminate: false,
      startForeground: true,
      syncThreshold: 5,
      maxLocation: 10,
      url: `${API_ADDRESS}/users/geolocation`,
      httpHeaders: {
        'Access-Control-Allow-Credentials': true,
        cookie: `pandemic_session=${cookie.pandemic_session}`,
      },
      postTemplate: {
        lat: '@latitude',
        long: '@longitude',
      },
    });
BackgroundGeolocation.on('location', location => {
  // handle your locations here
  // to perform long running operation on iOS
  // you need to create background task
  BackgroundGeolocation.startTask(async taskKey => {
    // execute long running task
    // eg. ajax post location
    // IMPORTANT: task has to be ended by endTask
    BackgroundGeolocation.endTask(taskKey);
  });
});

BackgroundGeolocation.on('stationary', stationaryLocation => {
  // handle stationary locations here
  // Actions.sendLocation(stationaryLocation);
});

BackgroundGeolocation.on('error', error => {
  console.log('[ERROR] BackgroundGeolocation error:', error);
});

BackgroundGeolocation.on('start', () => {
  console.log('[INFO] BackgroundGeolocation service has been started');
});

BackgroundGeolocation.on('stop', () => {
  console.log('[INFO] BackgroundGeolocation service has been stopped');
});

BackgroundGeolocation.on('authorization', status => {
  console.log(
    '[INFO] BackgroundGeolocation authorization status: ' + status,
  );
  if (status !== BackgroundGeolocation.AUTHORIZED) {
    // we need to set delay or otherwise alert may not be shown
    setTimeout(
      () =>
        Alert.alert(
          'App requires location tracking permission',
          'Would you like to open app settings?',
          [
            {
              text: 'Yes',
              onPress: () => BackgroundGeolocation.showAppSettings(),
            },
            {
              text: 'No',
              onPress: () => console.log('No Pressed'),
              style: 'cancel',
            },
          ],
        ),
      1000,
    );
  }
});

BackgroundGeolocation.on('background', () => {
  console.log('[INFO] App is in background');
});

BackgroundGeolocation.on('foreground', () => {
  console.log('[INFO] App is in foreground');
});

BackgroundGeolocation.on('abort_requested', () => {
  console.log('[INFO] Server responded with 285 Updates Not Required');

  // Here we can decide whether we want stop the updates or not.
  // If you've configured the server to return 285, then it means the server does not require further update.
  // So the normal thing to do here would be to `BackgroundGeolocation.stop()`.
  // But you might be counting on it to receive location updates in the UI, so you could just reconfigure and set `url` to null.
});

BackgroundGeolocation.on('http_authorization', () => {
  console.log('[INFO] App needs to authorize the http requests');
});

BackgroundGeolocation.checkStatus(status => {
  console.log(
    '[INFO] BackgroundGeolocation service is running',
    status.isRunning,
  );
  console.log(
    '[INFO] BackgroundGeolocation services enabled',
    status.locationServicesEnabled,
  );
  console.log(
    '[INFO] BackgroundGeolocation auth status: ' + status.authorization,
  );

  // you don't need to check status before start (this is just the example)
  if (!status.isRunning) {
    BackgroundGeolocation.start(); //triggers start on start event
  }
});

// you can also just start without checking for status
// BackgroundGeolocation.start();

}

componentWillUnmount() { // unregister all event listeners BackgroundGeolocation.removeAllListeners(); } render() { return <></>; } }

export default BgTracking; `

Expected Behavior

Actual Behavior

Possible Fix

Steps to Reproduce

1. 2. 3. 4.

Context

Debug logs

2020-09-24 14:25:05.359950+0700 StayHome[17874:281546] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFBoolean length]: unrecognized selector sent to instance 0x7fff80634318' First throw call stack: ( 0 CoreFoundation 0x00007fff23e3cf0e exceptionPreprocess + 350 1 libobjc.A.dylib 0x00007fff50ba89b2 objc_exception_throw + 48 2 CoreFoundation 0x00007fff23e5dc34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x00007fff23e4190c __forwarding + 1436 4 CoreFoundation 0x00007fff23e43bf8 _CF_forwarding_prep_0 + 120 5 CFNetwork 0x00007fff23115bbb _CFHTTPServerResponseEnqueue + 42745 6 CFNetwork 0x00007fff2300c121 _CFStreamErrorFromCFError + 7271 7 CFNetwork 0x00007fff22fa13ba CFURLRequestAppendHTTPHeaderFieldValue + 229 8 StayHome 0x0000000102e0f471 -[MAURPostLocationTask post:toUrl:withTemplate:withHttpHeaders:error:] + 1025 9 StayHome 0x0000000102e0ebab __28-[MAURPostLocationTask add:]_block_invoke + 891 10 libdispatch.dylib 0x0000000106737f11 _dispatch_call_block_and_release + 12 11 libdispatch.dylib 0x0000000106738e8e _dispatch_client_callout + 8 12 libdispatch.dylib 0x000000010674a56d _dispatch_root_queue_drain + 819 13 libdispatch.dylib 0x000000010674aca6 _dispatch_worker_thread2 + 135 14 libsystem_pthread.dylib 0x00007fff51c089f7 _pthread_wqthread + 220 15 libsystem_pthread.dylib 0x00007fff51c07b77 start_wqthread + 15 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Yrsafam commented 3 years ago

In my case it was fixed httpHeader: 'Access-Control-Allow-Credentials': true -> 'Access-Control-Allow-Credentials': 'true'. Previously, I removed this header altogether and the problem persisted...

xgenem commented 2 years ago

Wow this issue is old.