【アプリを作ろう】Expo + React Native + amplify【プッシュ通知編】

ReactNative(expo)を使い、amplifyで認証機能を実装して、
expoのプッシュ通知が動くかを実機端末で確認してみます。

CLI install

yarn add global expo-cli

プロジェクト作成

expo init expo-amplify

AWS Amplify ライブラリのローカル依存関係をinstall

cd expo-amplify
yarn add aws-amplify aws-amplify-react-native
yarn start
yarn add global @aws-amplify/cli
amplify configure
amplify init

認証機能を実装

amplify add auth
amplify push

App.js

import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Amplify from '@aws-amplify/core'
import config from './src/aws-exports'
import { withAuthenticator } from 'aws-amplify-react-native'
Amplify.configure(config)
function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.tsx to start working on your app!</Text>
    </View>
  )
}
export default withAuthenticator(App, {includeGreetings: true})
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

通知機能を実装

App.js

import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Amplify from '@aws-amplify/core'
import config from './src/aws-exports'
import { withAuthenticator } from 'aws-amplify-react-native'
import { Notifications } from 'expo'
import * as Permissions from 'expo-permissions'
import Constants from 'expo-constants'

Amplify.configure(config)

const App = () => {
  registerForPushNotificationsAsync = async () => {
    if (Constants.isDevice) {
      const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS)
      let finalStatus = existingStatus
      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('実機端末を使用してください。')
    }
  }

  React.useEffect(() => {
    registerForPushNotificationsAsync()
  }, [])

  return (
    <>
      <View style={styles.container}>
        <WelcomeScreen />
      </View>
    </>
  )
}

export default withAuthenticator(App, {includeGreetings: true})

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

Expoアプリをインストール

iPhone(実機端末)にExpoをinstallして開くと、上で書いたtokenがアラート表示されます。
そのtokenをメモってください。
下記のテストサイトで使います。

* ExponentPushToken[**********]
こんな感じで[]の中だけではなく全てメモってください。

Expoサイトから端末にテスト送信

https://expo.io/dashboard/notifications

画像出典:Expo — Push notification tool
画像出典:Expo — Push notification tool
画像出典:Expo — Push notification tool

*「Send a notification」をクリックする前に、
プッシュ通知なのでExpoアプリはバックグラウンドにしてください。

送信!これで届きます。

unsplash-logoTyler Lastovich

Photo by Tyler Lastovich on Unsplash