LoginSignup
1
2

More than 3 years have passed since last update.

Expo + Notification を初めてみる

Last updated at Posted at 2019-08-05

MacがないけどIphoneに通知が送りたい!

アプリ開発の授業中にふとこんな思いが胸中を巡り、たどり着いたのは Expo でした。

Expo はJavaScript(フレームワークの主はReact)で簡単に Android, IOS のアプリを開発することを助けるツールです。

とりあえずアプリで通知を送る前に、まずはオンラインのエディタとCurlを用いて通知を送ってみたいと思います。

アプリをインストールする

Iphoneで Expo Client をインストールして、アカウントをつくっておいてください。

まずはオンラインエディタを使ってみる

Expoのオンラインエディタは、Expo Snack というサイトで、ウェブで簡単に Expo のアプリケーションを作ることが出来ます。今回はCurlを用いて通知を送るために、ExponentTokenID というものを得るためのアプリケーション()を作ります。

ソースコードは次のようになります。これを App.js へ書いて下さい。(書いたもの https://snack.expo.io/@elect/device-push-token)

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

//取得のためのコード
async function registerForPushNotificationsAsync() {

  //warningがでるのを防ぐためにtry catchを入れる
  try {

    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;
    }

    this.token = await Notifications.getExpoPushTokenAsync();
    // this.token = token
    //コンソールに出力
    console.log(this.token);

  } catch (error) {
    console.log(error);
  }
  return this.token;
}


export default class App extends React.Component {
  componentDidMount() {
    //呼び出し
    let token = registerForPushNotificationsAsync();
  }
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>token: {token}</Text>
      </View>
    );
  }
}

{token} で赤い線が出ていますが、無視して下さい。上手く行きます

Expo Client経由でExpoアプリを見てみる。

Expo Snack の右側を見て下さい。
image.png

デバイスが見えますね。この Run on your device をクリックすると、ログインを求められます。
ログインすると、Projects という欄から使っているアプリを選択できるようになっているので、これを起動します。

アプリを開くと、
token: ExponentPushToken[...] という文字が見られると思うので、こいつをメモして下さい。

メモしたものを使って Curl で通知を送ってみましょう。

Curl を使って Iphone に通知を行う

アプリを落としてから、
お使いのターミナルで次のコマンドを入力して下さい。

curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
  "to": "ExponentPushToken[<yourtoken>]",
  "title":"hello",
  "body": "world"
}'

あなたのIphoneに素敵な通知が得られます。

参考

1
2
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
1
2