LoginSignup
10
20

More than 5 years have passed since last update.

ReactNative(Expo) & Firebase 入門

Last updated at Posted at 2018-12-25

紹介

  • Expo: ReactNativeというフレームワークを用いてiOS&Androidアプリを一つのコードで開発できるツールです。Expoというツールだけで簡単にビルドやエミュレータの環境が用意されています。アプリ開発初心者が躓きがちな環境構築(Android StudioやSDKの導入)をする手間が大幅に少なく、簡単にスタートできます。
  • Firebase: Googleが提供する無料で利用できるアプリ開発のためのプロットフォームです。クラウドでスマホアプリ&WEBアプリ向けにログイン機能やデータベースサービスなどが提供されており、自前のデータベースサーバーの構築やコーディング作業の削減になります。

Firebase

Firebaseにて作業します。

プロジェクト作成

  1. Googleアカウントでログイン
  2. 新規プロジェクトを作成

データベース(Cloud Firestore)構築

  1. 左のダッシュボードから「Firestore」→「データベースの作成」を選択。
  2. セキュリティルールで「テストモードで開始」を選択。
  3. これでデータベースの作成が完了です。

ルールの設定
Firestoreの「ルール」にてアクセス権限を細かく設定できます。
1. デフォルト

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}
  1. データベースへのアクセスをログインしているユーザーにのみ許可する場合
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

authentication(認証機能)

  • ログイン機能の使い方。
  1. 左側のダッシュボードから「Authentication」を選択。
  2. ログイン不要な場合は「匿名」、ログインする場合、メール/パスワード、Google、Facebookなど主要なプロバイダを選択して有効にします。
  3. 「ウェブアプリにFirebaseを追加」を選択。
  4. <script>タグに囲まれているコードを後ほどExpo側で利用します。

Expo

ExpoプロジェクトでFirebaseを導入する

$ expo init <アプリ名>
$ cd <アプリ名>
$ npm i --save firebase // プロジェクトへFirebaseをインストール

初期化

firebase.js
import firebase from 'firebase';

// Firebase 初期化
const config = {
  apiKey: "********",
  authDomain: "********",
  databaseURL: "********",
  projectId: "********",
  storageBucket: "********",
  messagingSenderId: "********"
};
firebase.initializeApp(config);

// サインインしているかどうかの判定
firebase.auth().onAuthStateChanged(user => {
  if (!user) {
    // サインイン中でない
    console.log('Not sign in')
  } else {
  // サインイン中。画面遷移などの処理をする。
    console.log('Signed in');
  }
})

// サインインしているかどうかの判定2
const currentUser = firebase.auth().currentUser

// メール&パスワードログイン
export const login(email, password){
  firebase.auth().signInWithEmailAndPassword(email, password)
  .then(response => {
    alert("Login Success!");
  })
  .catch(error => {
    alert(error.message);
  });
}

// ユーザ登録
export const signup(email, password){
  firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(user => {
    if (user) {
      console.log("Success to Signup")
    }
  })
  .catch(error => {
    console.log(error);
  })
}

// Facebookログイン
export const FBLogin = async () => {
  const { type, token } = 
    await Expo.Facebook.logInWithReadPermissionsAsync('********', 
      { permissions: ['public_profile'] 
    })
  if (type === 'success') {
    // Build Firebase credential with the Facebook access token.
    const credential = firebase.auth.FacebookAuthProvider.credential(token)
    // Sign in with credential from the Facebook user.
    firebase
      .auth().signInAndRetrieveDataWithCredential(credential)
      .then(user => {
        console.log('connected to firebase')
      })
      .catch(error => {
        console.error(error)
        // Handle Errors here.
      })
  }
}

// サインアウト処理
export const logout = () => {
  firebase.auth().signOut()
    .then(result => {
      console.log(result)
    })
    .catch(error => {
      console.log(error)
    })

export default firebase
  • ログイン画面など任意のコンポーネントにインポートし、ボタンのonPress各メソッドを呼び出して登録、ログイン、ログアウトが実行できます。
  • FacebookログインをするにはFacebookアプリを作成し設定する必要があります。  

参考

Expo で Firebase Authentication で認証する
React Native + Expo + firebaseで認証を行う
Firebase Authentication これだけは覚えておけ!テストに出るぞ!
Firebase AuthenticationでReactアプリにTwitter/Facebook/Google認証をつける
React+Redux+Firebase Authenticationでログイン/ログアウト機能を実装する (1)

React Native入門: FirebaseのCloud Firestoreでレコーディングダイエットアプリを作ってみる(前編)
React + Redux + Firebaseで作るTodo App

10
20
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
10
20