Skip to content

Instantly share code, notes, and snippets.

@sjchmiela
Created April 6, 2020 16:16
Show Gist options
  • Save sjchmiela/d8f11af638f739ab648ad3c192f3568f to your computer and use it in GitHub Desktop.
Save sjchmiela/d8f11af638f739ab648ad3c192f3568f to your computer and use it in GitHub Desktop.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleSuccess: notificationIdentifier => {
// dismiss every notification immediately after it is presented
Notifications.dismissNotificationAsync(notificationIdentifier);
},
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
}),
});
const NOTIFICATION_IDENTIFIER = 'whatever';
export default function App() {
React.useEffect(() => {
Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowAnnouncements: true,
allowSound: true,
}
});
}, []);
const showNotification = React.useCallback(() => {
Notifications.scheduleNotificationAsync({
identifier: NOTIFICATION_IDENTIFIER,
content: {
title: 'Hello there!',
body: 'Here is the body.',
},
trigger: null,
})
}, []);
const scheduleNotification = React.useCallback(() => {
Notifications.scheduleNotificationAsync({
identifier: NOTIFICATION_IDENTIFIER,
content: {
title: 'Hello there!',
body: 'Here is the body.',
},
trigger: { seconds: 5 },
})
}, []);
const dismissNotification = React.useCallback(() => {
Notifications.dismissNotificationAsync(NOTIFICATION_IDENTIFIER);
}, []);
return (
<View style={styles.container}>
<Text>First, show the notification immediately, notice it will not stay in the Notification Center.</Text>
<Button onPress={showNotification} title="Show push notification immediately" />
<Text>Then, schedule the notification and background the app. Notice the notification stays in the Notification Center.</Text>
<Button onPress={scheduleNotification} title="Show push notification in 5 seconds" />
<Text>Dismiss the notification. It should be removed from the Notification Center.</Text>
<Button onPress={dismissNotification} title="Dismiss the notification" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 20,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment