Skip to content

Instantly share code, notes, and snippets.

@manoj-nama
Created December 13, 2017 09:38
Show Gist options
  • Save manoj-nama/ebe2333442b9eb329936b6c3a92caa46 to your computer and use it in GitHub Desktop.
Save manoj-nama/ebe2333442b9eb329936b6c3a92caa46 to your computer and use it in GitHub Desktop.
Expo Push Notifications for React Native
import React from 'react';
import {
View,
Button,
Text,
Image,
AsyncStorage
} from 'react-native';
import { StorageKeys } from './config/constants';
import { Permissions, Notifications, Constants } from 'expo';
export default class App extends React.Component {
state = {
token: ''
}
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
if(status !== 'granted' || status !== 'undetermined') {
alert("Permissions not granted");
return;
}
// Bind a notification handler
this.notificationHandler = Notifications.addListener(this.handlePush);
}
handlePush = notification => {
console.log(">>", notification);
this.setState({ notification });
}
show = async () => {
console.log("presenting...");
const data = await Notifications.presentLocalNotificationAsync({
title: "My Awesome Title",
body: "Thsis is a local notification",
data: { some: { data: "that we can use" } }
});
}
schedule = async () => {
console.log("scheduling...");
const data = await Notifications.scheduleLocalNotificationAsync({
title: "My Awesome Title",
body: "Thsis is a schduled local notification",
data: { some: { data: "schduled local notification" } }
}, {
time: (new Date()).getTime() + 5000
});
}
getToken = async () => {
const token = await Notifications.getExpoPushTokenAsync();
console.log("Token:", token);
this.setState({ token });
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={this.getToken} title={'get Token'} />
<Button onPress={this.show} title={'Show Local Notif.'} />
<Button onPress={this.schedule} title={'Schedule Local Notif.'} />
<Text>DeviceToken: {this.state.token}</Text>
{
this.state.notification ?
<Text>{JSON.stringify(this.state.notification, null, 2)}</Text> :
<Text>Waiting for a push...</Text>
}
</View>
)
}
}
/*
curl -H "Content-Type: application/json" -X POST https://exp.host/--/api/v2/push/send -d '{
"to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
"title":"hello",
"body": "world"
}'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment