Skip to content

Instantly share code, notes, and snippets.

@IgorHalfeld
Created December 8, 2022 00:37
Show Gist options
  • Save IgorHalfeld/9cbd1044ef81d780b80f5e8b7713eff8 to your computer and use it in GitHub Desktop.
Save IgorHalfeld/9cbd1044ef81d780b80f5e8b7713eff8 to your computer and use it in GitHub Desktop.
import { Platform } from 'react-native';
import {
check,
request,
PERMISSIONS,
RESULTS,
openSettings,
} from 'react-native-permissions';
interface PermissionAlertOptions {
permissionName: string;
message?: string;
}
export const showPermissionAlert = ({
permissionName,
message,
}: PermissionAlertOptions): void => {
const msg = message ?? `Precisamos da sua permissão de ${permissionName}`;
const actions = [
{
label: 'Não',
onPress: () => {},
},
{
label: 'Continuar',
onPress: () => openSettings(),
},
];
alert('Permissão necessária', msg, { actions });
};
interface VertifyPermissionOptions {
ios: typeof PERMISSIONS.IOS;
// TODO: i don't know why I can't use typeof PERMISSION.ANDROID
android: any;
}
export const verifyPermission = async ({
ios,
android,
}: VertifyPermissionOptions): Promise<boolean> => {
const permission = Platform.select({
ios,
android,
});
const enabled = await check(permission);
return enabled === RESULTS.GRANTED;
};
interface RequestPermissionOptions {
message?: string;
permissionName: string;
permissions: VertifyPermissionOptions;
}
export const requestPermission = ({
message,
permissionName,
permissions,
}: RequestPermissionOptions): Promise<boolean> => {
return new Promise(async (resolve) => {
const locationMessage =
message || `Precisamos da sua permissão de ${permissionName}.`;
const permission = Platform.select({
ios: permissions.ios,
android: permissions.android,
});
const enabled = await check(permission);
if (enabled === RESULTS.GRANTED) return resolve(true);
if (enabled === RESULTS.UNAVAILABLE) return resolve(false);
if (enabled === RESULTS.DENIED) {
showPermissionAlert({ permissionName, message });
}
return enabled;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment