react-native-firebase の使い方
「react-native-firebase」の使い方をまとめました。
前回
1. react-native-firebase
「react-native-firebase」は、「React Native」用のFirebase実装です。すべてのFirebaseサービスで iOS と Android の両プラットフォームをサポートしています。
2. react-native-firebaseの使い方
「react-native-firebase」の使い方は、次のとおりです。
2-1. React Nativeプロジェクトの作成
(1) React Nativeプロジェクトの作成。
npx react-native init my_app
cd my_app
(2) パッケージのインストール。
今回は、「Firebase Analytics」を使うので、analyticsもインストールします。
npm install @react-native-firebase/app
npm install @react-native-firebase/analytics
2-2. Firebaseプロジェクトの作成
(1) Firebaseコンソールでプロジェクトを作成。
2-3. Androidのセットアップ
(1) FirebaseコンソールのプロジェクトでAndroidアプリを追加し、「google-services.json」をダウンロードして、React Nativeプロジェクトの「android/app」に配置。
(2) React Nativeプロジェクトの「android」を「Android Studio」で開き、「android/build.gradle」と「android/app/build.gradle」を編集。
・android/build.gradleの一部
buildscript {
:
dependencies {
classpath 'com.google.gms:google-services:4.4.0'
:
}
}
・android/app/build.gradleの一部
apply plugin: 'com.google.gms.google-services'
:
dependencies {
:
// Firebase BOMを使用してすべてのFirebaseライブラリのバージョンを管理
implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
// Firebaseライブラリを追加(バージョンはBOMによって管理される)
implementation("com.google.firebase:firebase-analytics-ktx")
}
2-4. iOSのセットアップ
(1) FirebaseコンソールのプロジェクトでiOSアプリを追加し、「GoogleService-Info.plist」をダウンロード。
(2) React Nativeプロジェクトの「ios/Profile」の「target 'ターゲット名' do」の「config = use_native_modules!」の下で追加パッケージを指定。
target 'my_app' do
config = use_native_modules!
pod 'FirebaseCore', :modular_headers => true;
pod 'FirebaseAnalytics', :modular_headers => true;
pod 'GoogleUtilities', :modular_headers => true;
詳しくは、以下のstackoverflowを参照。
(3) podのインストール。
cd ios
pod install
cd ..
(4) Xcodeで「ios」内のworkspaceを開き、「GoogleService-Info.plist」を追加。
(5) AppDelegate.mmの編集。
・AppDelegate.mmの一部
:
#import <Firebase.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
:
(6) Xcodeで署名し、iPhoneにインストールできることを確認。
2-4. Firebase Analyticsへのイベント送信
(1) コードの編集。
・App.tsx
import { Button, SafeAreaView } from 'react-native';
import analytics from '@react-native-firebase/analytics';
// アプリ
const App: React.FC = () => {
// ボタンクリック時に呼ばれる
const onClick = async () => {
await analytics().logEvent('hello_event');
console.log("done!");
};
return (
<SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button
onPress={onClick}
title="Analyticsにイベント送信"
/>
</SafeAreaView>
);
};
export default App;
(3) コードの実行。
ボタンを押すと、FirebaseのAnalyticsにhello_eventが投げられていることを確認します (反映には数分から24時間かかる)。
npm start
関連
次回
この記事が気に入ったらサポートをしてみませんか?