Handling permissions in Expo
expo install expo-permissions
- You can check if a permission is granted with
Permissions.getAsync(...permissionTypes)
and ask for a permission withPermissions.askAsync(...types)
- Both return a
Promise
with hasstatus
andexpires
as well as details about scope - The
status
is usuallygranted
ordenied
. It could also beundetermined
in case ofPermissions.NOTIFICATIONS
for iOS, as iOS does not disambiguateundetermined
fromdenied
- Make sure you're basing your logic on
granted
and!granted
to account for cases likeundetermined
that only happen on iOS and only for some permissions - on iOS remote notifications only show if
allowsSound
,allowsAlert
orallowsBadge
is set.
There are about a dozen permission types
- NOTIFICATIONS
- USER_FACING_NOTIFICATIONS
- LOCATION
- CAMERA
- AUDIO_RECORDING
- CONTACTS
- CAMERA_ROLL
- CALENDAR
- REMINDERS
- SYSTEM_BRIGHTNESS
- MOTION
async function alertIfRemoteNotificationsDisabledAsync() {
const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS)
if (status !== 'granted') {
alert('Hey! You might want to enable notifications for my app, they are good.')
}
}
async function checkMultiPermissions() {
const { status, expires, permissions } = await Permissions.getAsync(Permissions.CALENDAR, Permissions.CONTACTS)
if (status !== 'granted') {
alert('Hey! You heve not enabled selected permissions')
}
}
Here's an example asking for permissions for push notifications..
const askPermissions = async () => {
// See if app already has permission
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS)
let finalStatus = existingStatus
// No existing permisson, ask for it
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS)
finalStatus = status
}
// Permission denied
if (finalStatus !== 'granted') {
return false
}
return true
}