Source: https://developers.woosmap.com/products/geofencing-sdk/react-native-plugin/guides/setup/

> For clean Markdown of any page, append `.md` to the page URL.

> For a complete documentation index, see https://developers.woosmap.com/llms.txt

# React Native Plugin



The Woosmap Geofencing SDK allows you to monitor Geofences, track your user's location and connect with the Woosmap Search and Distance APIs.

Find Geofencing React Native library release notes in the [CHANGELOG.md file](https://www.npmjs.com/package/@woosmap/react-native-plugin-geofencing?activeTab=code) on npm website.

## Install the React Native Plugin

### Prerequisites

Before you begin, make sure you have installed and setup React Native on your machine.
See this [Get Started on official React Native Documentation](https://reactnative.dev/docs/getting-started).

### Installation

Add the Woosmap Geofencing React Native plugin to your project using this command line:

```shell
npm install @woosmap/react-native-plugin-geofencing
```

### Supported Platforms

- iOS (Plugin supports iOS 15 and higher)
- Android (Plugin supports Android 9 and higher)

**App closed limitations**

Because of the React Native framework, callbacks are not triggered when the application is closed.
Locations and geofence events are well stored in the device, and you can retrieve them through getter methods included in this plugin.

**Adding the platform**

For iOS

- **info.plist**: Please check info.plist updated with following keys:
  - NSLocationAlwaysAndWhenInUseUsageDescription
  - NSLocationAlwaysUsageDescription
  - NSLocationWhenInUseUsageDescription
  - UIBackgroundModes

```xml
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Used to test the library</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Used to test the library</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Used to test the library</string>
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>location</string>
</array>
```

- **Podfile**: configure to use `use_frameworks!` and `platform :ios, '15.0'`
  if you are using **Mac M1** architecture, update pod post installation as:

```
post_install do |installer|
installer.pods_project.targets.each do |target|
  target.build_configurations.each do |config|
        config.build_settings["ONLY_ACTIVE_ARCH"] = "NO"
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0'
    end
  end
end
```

### Duplicate WoosmapGeofencing.xcframework-ios.signature During Archive Adding the platform

When archiving an app in Xcode, you may encounter the following error:

> “WoosmapGeofencing.xcframework-ios.signature” couldn’t be copied to “Signatures” because an item with the same name already exists.

This occurs due to a duplicate signature file created during the build process.

**_Solution_**

Add the following script in your project’s **Build Phases → Run Script** section:

```sh
echo "Removing duplicate WoosmapGeofencing signature file..."
rm -rf "$BUILD_DIR/${CONFIGURATION}-iphoneos/WoosmapGeofencing.xcframework-ios.signature"
```

Then enable the checkbox: ✔ **For Install build only**

After adding this script, clean and rebuild your project. Archiving should now complete without this error.

### Modules

- **WoosmapGeofencing**: Woosmap contains methods to monitor location, regions.

### Objects(Read Only)

- **Location**: Represents the location object
- **POI**: Represents Point of Interest
- **Region**: Represents a geographical region/Geofence

## Usage

```js
import WoosmapGeofencing from "@woosmap/react-native-plugin-geofencing";
```

### Check and request permissions

Before initializing the SDK it is required that you request for required location permissions.

To check if the location permissions are granted by the user call `getPermissionsStatus` method.

```js
WoosmapGeofencing.getPermissionsStatus()
        .then((status: string) => {
          console.log(status);
        })
        .catch((error: any) => {
          alert('message: ' + error.message);
        });
```

Parameter status will be a string, one of:

- `GRANTED_BACKGROUND` : User has granted location access even when app is not running in the foreground.
- `GRANTED_FOREGROUND` : Location access is granted only while user is using the app.
- `DENIED`: Location access is denied.
- `UNKNOWN`: Without providing or denying any permission then it will return unknown.

**_Please note_**: Plugin will not work as expected if location access is denied.

**Requesting location access**
To request location access call `requestPermissions` method of the plugin. This will result in displaying location access permission dialog. This method accepts a boolean parameter `isBackground`. If this parameter is set to true, then plugin will ask for background location access. Code snippet below asks for background location access.

```js
WoosmapGeofencing.requestPermissions(props.background)
        .then((status: string) => {
          console.log(status);
        })
        .catch((error: any) => {
          alert('message: ' + error.message);
        });
```

**Check Bluetooth permissions**

In order to get beacon-fencing running on Android devices you need to make sure that all the Bluetooth related permissions are granted to the plugin.

To check if the Bluetooth permissions are granted by the user call `getBLEPermissionsStatus` method.

```javascript
WoosmapGeofencing.getBLEPermissionsStatus()
      .then((status: string) => {
        console.log(status);
      })
      .catch((error: any) => {
         alert('message: ' + error.message);
      });
```

Parameter status will be a string, one of:

- `GRANTED` : User has granted bluetooth access.
- `DENIED`: Bluetooth access is denied.
- `BACKGROUND_LOCATION_DENIED`: Background location access is denied. You first need to request background location permission.

**Requesting Bluetooth permissions**

To request Bluetooth access call `requestBLEPermissions` method of the plugin. This will result in displaying Bluetooth access permission dialog.

```javascript
WoosmapGeofencing.requestBLEPermissions()
      .then((status: string) => {
        console.log(status);
      })
      .catch((error: any) => {
         alert('message: ' + error.message);
      });

```

**_Note_**: For beacon-fencing to work you will also need to request background location access. To request background location access please invoke `requestPermissions` method of the plugin with background parameter enabled.

### Initializing the plugin

The plugin automatically sends the required authentication headers (`X-Api-Key` and platform identifiers) with every API request. If you're calling Woosmap REST APIs directly without the plugin, you'll need to set these headers yourself. See [Authenticating from Mobile Apps](/api-reference/authentication/#authenticating-from-mobile-apps-or-server-side-via-headers) for details.

Plugin can be initialized by simply calling `initialize` method.

```js
var woosmapSettings: WoosmapGeofencingOptions = {
  privateKeyWoosmapAPI: "<<WOOSMAP_KEY>>",
  trackingProfile: "liveTracking"
};
WoosmapGeofencing.initialize(woosmapSettings)
        .then((value: string) => {
          console.log(value);
        })
        .catch((error: any) => {
          alert('message: ' + error.message);
        });
```

Both configuration options `privateKeyWoosmapAPI` and `trackingProfile` are optional. You can also initialize the plugin by passing null configuration.

```js
await WoosmapGeofencing.initialize();
```

You can also set the Woosmap API key later by calling `setWoosmapApiKey` method.

```js
WoosmapGeofencing.setWoosmapApiKey(privateKeyWoosmapAPI)
        .then((value: string) => {
          console.log(value);
        })
        .catch((error: any) => {
          alert('message: ' + error.message);
        });
```

### Notifications on Android devices

Geofencing SDK uses foreground service on Android when using `liveTracking` and `optimalPassiveTracking` profile. The SDK needs to show an ongoing notification in order to work properly while tracking using these profiles.

You need to make sure that permission to post notification is granted before initiating tracking with `liveTracking` and `optimalPassiveTracking`.

To request permission invoke `requestNotificationPermissions` method.

```js
WoosmapGeofencing.requestNotificationPermissions()
      .then((value: string) => {
        console.log(value);
      })
      .catch((error: any) => {
        console.error(error);
      });
```

### Customize notifications on Android devices

Notifications on Android devices can be customized using following configuration options. These options should be passed wile initializing the plugin.

- **`androidNotificationTitle`**: Title of the notification.
- **`androidNotificationText`**: Content text of the notification.
- **`androidNotificationIconName`**: Set the notification icon name from Android `drawable` or `mipmap` folder.
- **`androidNotificationIconUrl`**: Set the notification icon fron RN assets by providing the asset path.

```js
const asset = Image.resolveAssetSource(require('../../assets/ic_alarm.png'));
var woosmapSettings: WoosmapGeofencingOptions = {
  androidNotificationText: 'Plugin Geofencing is running',
  androidNotificationTitle: 'Woosmap Geofencing',
  androidNotificationIconUrl: asset.uri,
};

WoosmapGeofencing.initialize(woosmapSettings)
      .then((value: string) => {
        console.log(value);
      })
      .catch((error: any) => {
        console.error(error);
      });
```

### Listening to location event

To listen to location, call `watchLocation` method. Method will invoke callback and pass a location object as a parameter. Method will return a watchId . This id can be used to remove a callback.

```js
const callback = (value: Location) => {
  alert('message: ' + JSON.stringify(value));
};

WoosmapGeofencing.watchLocation(callback)
        .then((watchRef: string) => {
          //Keep watchRef, it requires when you wish to remove location watch.
          console.log('Watch added');
        })
        .catch((error: any) => {
          alert('message: ' + error.message);
        });
```

To stop getting location updates:

```js
WoosmapGeofencing.clearLocationWatch(watchID)
        .then((watchRef: string) => {
          console.log(watchRef);
        })
        .catch((error: any) => {
          alert('message: ' + error.message);
        });
```

### Get locations from the local database

Call `getLocations` method to get an array of Locations from the local db.

```js
WoosmapGeofencing.getPois(locationId) //locationId is optional
        .then((value: Location[]) => {
          console.log(String(value.length));
        })
        .catch((error: any) => {
          console.error(error);
        });
```

### Delete all locations from the local database

Call `removeLocations` method to remove all locations in the local db.

```js
WoosmapGeofencing.removeLocations()
        .then((value: string) => {
          console.log(value);
        })
        .catch((error: any) => {
          console.error(error);
        });
```
