How to add permissions on app
Introduction
In this guide, we will learn how to add permissions on the app. We will use the app-permissions
plugin to add permissions on the app.
How to add permissions on the app
Below is an example on adding permissions for location and camera on the app. It will request for the permissions when the app is opened since we are adding in root component.
Similarly, you can add the permissions code in any component where you want to request for the permissions. It can be added in the useEffect hook of the component.
You can add any number of permissions in the permissions
array.
import React, { useEffect } from "react";
import { PERMISSIONS , requestMultiple } from "react-native-permissions";
import { appPluginStoreApi } from "@appmaker-xyz/core";
import { Platform } from "react-native";
const checkPermission = async (permission, permissions) => {
if (permissions && permissions.length > 0) {
const permissionIndex = permissions.findIndex(
(p) => p.permission === permission
);
if (permissionIndex !== -1) {
return true;
}
}
return false;
}
const CustomComponent = () => {
useEffect(() => {
const permissions =
appPluginStoreApi()?.getState()?.plugins?.["app-permissions"]?.settings
?.permissions;
const platformPermissions = [];
// permissions = [{permission: "location"}, {permission: "camera"}]
if(checkPermission('camera', permissions)){
if (Platform.OS === "ios") {
platformPermissions.push(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
} else {
platformPermissions.push(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
}
}
requestMultiple(platformPermissions)
.then((statuses) => {
console.log("permissions", statuses);
})
.catch((err) => {
console.log("permissions->error", err);
});
}, []);
return null;
};
addFilter("app-custom-root-components", "test-case", (currentComponents) => {
currentComponents?.push(CustomComponent);
return currentComponents;
});
// whole code should be placed outside activate function
function activate() {
console.log("Activated");
}
In the above code, we are adding the CustomComponent
in the root component. We are checking if the permissions are added in the app-permissions
plugin settings. If the permissions are added, we are requesting for the permissions.