LoginSignup
25
22

More than 5 years have passed since last update.

create-react-native-appとexpoを使って10分でプッシュ通知を試す

Last updated at Posted at 2017-03-31

Requirements

  1. node.jsがインストールされていること。
  2. android/iPhoneどちらか持っていること。
  3. curlがインストールされていること。

create-react-native-appのインストール

npm install -g create-react-native-app

expoを手持ちのスマホにインストール

インストールはこちらから

プロジェクトの作成

create-react-native-app my-stupid-project

とりあえず起動してみる

cd my-stupid-project && npm start

起動するとデカイQRコードが表示されるので、先ほどスマホにインストールしたexpoアプリで読み込む。すると以下のような画面が表示されると成功。
IMG_0033.PNG

プッシュ通知を実装する

App.jsを開いて以下のように修正する。

import React, { Component } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Expo, { Permissions, Notifications } from 'expo'

async function registerPushNotificationService() {
  const { status } = await Permissions.askAsync(Permissions.REMOTE_NOTIFICATIONS)
  if (status !== 'granted') {
    return
  }
  const token = await Notifications.getExponentPushTokenAsync()
  console.log('!!!!! my token is:', token)
}

export default class App extends Component {
  state = { notifications: null }
  componentWillMount() {
    registerPushNotificationService()
    this.listeners = Notifications.addListener(this.onPushNotification)
  }
  onPushNotification = (notifications) => { this.setState({notifications})}
  render() {
    return (
      <View style={styles.container}>
        <Text>Hello world!</Text>
        { this.state.notifications
          && <Text>{JSON.stringify(this.state.notifications)}</Text>
        }
      </View>
    )
  }
}

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

Expo.registerRootComponent(App)

Curlを使ってメッセージを送りつける

上記のコードを保存すると自動的にスマホ側にロードされ、expoのtokenが以下のようにコンソールに表示される。

5:00:55 PM: !!!!! my token is: ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]

expoにpush notificationのendpointがあるので、先ほどのトークンと共にメッセージを投げる

curl -iv -H 'accept: application/json' -H 'accept-encoding: gzip, deflate' -H 'content-type: application/json' -d '[{"to":"ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]", "body":"wut up", "badge": 1, "data":{"a":"b"}}]' https://exp.host/--/api/v2/push/send

すると結果が以下のように帰ってくれば成功。

{"data":[{"status":"ok"}]}

ちなみにスマホ側はこんな感じになる。
IMG_0034.PNG
IMG_0035.PNG

結論

expoめっちゃ便利!QRコードをシェアするだけで、他人に試してもらうことができる。iOSでは、ネイティブコードを簡単に配布することはできないが、expoのようにJSコードであれば、"今のところ"、ダイナミックにロードすることは禁止されていないため、このような方法で他人から容易にフィードバックがもらうことが可能になった。また、low levelの操作は、react-native/expoがあるので、ある程度はカバーできるが、それ以外の操作を行う場合は自分で作成する必要があり、自作したネイティブコードは、もちろんダイナミックにロードすることができないので注意が必要。個人的には、割とハードウェアへのアクセス要求がない、iOSとAndroidのチームを作るほどお金がないようなプロジェクトには使えるんじゃないでしょうか。ちなみに、私はモバイル門外漢ですけど(笑)では、長くなってしまったので、皆様よい週末をお過ごしください!

25
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
22