expo push通知に関して
expoにおいてpush通知関連の参考コード
※ コマンドラインでexpoに予めログインしていないとpush tokenを取得できません。
push tokenの作成
フロントエンドの実装
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Notifications } from 'expo';
import * as Permissions from 'expo-permissions';
import Constants from 'expo-constants';
export default class App extends React.Component {
registerForPushNotificationsAsync = async () => {
// 実機端末か否かを判定
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
// ユーザーによる通知の許可or許可しないが決定していないときのみ
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
// ユーザーが通知許可しなかった場合は処理を抜ける
if (finalStatus !== 'granted') return;
// デバイストークンを取得する
let token = await Notifications.getExpoPushTokenAsync();
alert(token);
} else {
alert('プッシュ通知は、実機端末を使用してください。');
}
};
componentDidMount() {
this.registerForPushNotificationsAsync();
}
render () {
return (
<View>
<Text>Open up App.js to start working on your app!</Text>
</View>
);
}
}
pushの送信
バックエンドの実装(express)
expo-server-sdkのインストール
npm i expo-server-sdk
expressサーバーにて関数に下記を設定する
import Expo from 'expo-server-sdk';
//const { Expo } = require('expo-server-sdk')
// Create a new Expo SDK client
let expo = new Expo();
//以下は関数内に設定
// Create the messages that you want to send to clents
let messages = [];
for (let pushToken of somePushTokens) {
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
}
// Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications.html)
messages.push({
to: pushToken,
sound: 'default',
body: 'This is a test notification',
data: { withSome: 'data' },
})
}
// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
(async () => {
// Send the chunks to the Expo push notification service. There are
// different strategies you could use. A simple one is to send one chunk at a
// time, which nicely spreads the load out over time:
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
console.log(ticketChunk);
tickets.push(...ticketChunk);
// NOTE: If a ticket contains an error code in ticket.details.error, you
// must handle it appropriately. The error codes are listed in the Expo
// documentation:
// https://docs.expo.io/versions/latest/guides/push-notifications#response-format
} catch (error) {
console.error(error);
}
}
})();
...
// Later, after the Expo push notification service has delivered the
// notifications to Apple or Google (usually quickly, but allow the the service
// up to 30 minutes when under load), a "receipt" for each notification is
// created. The receipts will be available for at least a day; stale receipts
// are deleted.
//
// The ID of each receipt is sent back in the response "ticket" for each
// notification. In summary, sending a notification produces a ticket, which
// contains a receipt ID you later use to get the receipt.
//
// The receipts may contain error codes to which you must respond. In
// particular, Apple or Google may block apps that continue to send
// notifications to devices that have blocked notifications or have uninstalled
// your app. Expo does not control this policy and sends back the feedback from
// Apple and Google so you can handle it appropriately.
let receiptIds = [];
for (let ticket of tickets) {
// NOTE: Not all tickets have IDs; for example, tickets for notifications
// that could not be enqueued will have error information and no receipt ID.
if (ticket.id) {
receiptIds.push(ticket.id);
}
}
let receiptIdChunks = expo.chunkPushNotificationReceiptIds(receiptIds);
(async () => {
// Like sending notifications, there are different strategies you could use
// to retrieve batches of receipts from the Expo service.
for (let chunk of receiptIdChunks) {
try {
let receipts = await expo.getPushNotificationReceiptsAsync(chunk);
console.log(receipts);
// The receipts specify whether Apple or Google successfully received the
// notification and information about an error, if one occurred.
for (let receipt of receipts) {
if (receipt.status === 'ok') {
continue;
} else if (receipt.status === 'error') {
console.error(`There was an error sending a notification: ${receipt.message}`);
if (receipt.details && receipt.details.error) {
// The error codes are listed in the Expo documentation:
// https://docs.expo.io/versions/latest/guides/push-notifications#response-format
// You must handle the errors appropriately.
console.error(`The error code is ${receipt.details.error}`);
}
}
}
} catch (error) {
console.error(error);
}
}
})();
参考
push tokenの作成
Push Notifications
https://docs.expo.io/versions/latest/guides/push-notifications/
[React Native] ExpoのPush Notificationsでプッシュ通知する
http://www.aizulab.com/blog/expo-push-notifications-example/
pushの送信
expo-server-sdk-node
https://github.com/expo/expo-server-sdk-node
【React Native】【Expo】Expoでプッシュ通知を送る
https://tech.maricuru.com/entry/2018/04/23/185331
Author And Source
この問題について(expo push通知に関して), 我々は、より多くの情報をここで見つけました https://qiita.com/Daiki_k21/items/3dbf445526e2d90d65e7著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .