Created
December 8, 2022 00:37
-
-
Save IgorHalfeld/9cbd1044ef81d780b80f5e8b7713eff8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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