React Native’de Firebase ile Push Notification Gönderimi Nasıl Yapılır?

Zafer Ayan
7 min readMar 26, 2020

Önceki yazımda local notification gönderimi üzerine değinmiştim. Bu yazımda push notification gönderimi üzerine değineceğim.

Öncelikle projemizi aşağıdaki gibi oluşturalım ve ayağa kaldıralım:

npx react-native init SampleRNPushNotifications --template react-native-template-typescript
cd SampleRNPushNotifications
yarn ios

Gerekli kütüphaneleri yükleyelim:

yarn add react-native-push-notification \
@react-native-firebase/app@11.2.0 \
@react-native-firebase/messaging@11.2.0 \
@react-native-community/push-notification-ios \
@types/react-native-push-notification

Kütüphaneler ve işlevlerine değinmek gerekirse:

  • react-native-push-notification: Local notification gönderimi için gerekli olan kütüphane,
  • @react-native-firebase/app@11.2.0: Firebase servislerini kullanmak için eklenen ana kütüphane,
  • @react-native-firebase/messaging@11.2.0: Firebase Cloud Messaging (FCM) kullanımı için gereken kütüphane,
  • @react-native-community/push-notification-ios: iOS tarafında notification izinlerinin alınması için gereken kütüphane,
  • @types/react-native-push-notification: push notification için gerekli tipleri içeren kütüphanedir.

iOS kısmı için Cocoapod’ları yükleyelim:

npx pod-install

Bu aşamadan sonra Firebase hesabı oluşturmamız gerekiyor.

Firebase hesabının oluşturulması

Öncelikle console.firebase.google.com adresine giderek bir proje oluşturuyoruz:

Proje adını belirtiyoruz. Ben SampleRNPushNotification verdim:

Firebase analiz araçları eklensin mi diye soruyor. Enable kısmı seçili olarak devam edebiliriz:

Bir Google Analytics hesabı seçmenizi istiyor. Burada mevcut hesabınızı seçebilirsiniz:

Proje oluşturulup tamamlandığında “Your project is ready” mesajı ile size bildirilecektir:

Android için push notification mekanizmasının oluşturulması

Sol tarafta yer alan Project Overview kısmından Project Settings’i seçiyoruz:

Çıkan sayfada “Your apps” bölümünde Android’i seçelim:

1. Register App bölümünde uygulamanın paket adını giriyoruz. Paket adını bulmak için Android Studio’da build.gradle (Module: app) dosyasında defaultConfig kısmında yer alan applicationId değerini giriniz. Aşağıdaki gibi bulabilirsiniz:

cat android/app/build.gradle |pcregrep -o1 "applicationId \"(.+)\""

App nickname kısmına da uygulamanızın admin panelinde görüneceği adı giriniz.

Debug signing certificate kısmı için aşağıdaki komut yardımıyla SHA1 kodunu edinebilirsiniz:

keytool -list -v -keystore ./android/app/debug.keystore -storepass android |pcregrep -o1 "SHA1: (.+)"

2. Download config file aşamasında Firebase’in yapılandırma dosyasını indirip, Android Studio’da sol menüdeki app dizini üstüne sürükleyiniz. Projeyi Android Studio’da açmak için:

open -a /Applications/Android\ Studio.app ./android

3. Add Firebase SDK aşamasında uygulamaya analytics kütüphanesini ekliyoruz. Ekleme adımları aşağıdaki gibidir:

android/build.gradle içerisinde dependencies kısmına aşağıdaki koyu renk ile işaretli google-services kütüphanesini ekleyelim:

dependencies {
classpath("com.android.tools.build:gradle:4.1.0")
classpath 'com.google.gms:google-services:4.3.5'
// NOTE: Do not place your application dependencies here,
// they belong in the individual module build.gradle files
}

app/build.gradle içerisinde dosyanın en altına google services plugin’ini ekleyelim:

apply plugin: "com.google.gms.google-services"

Devamında dependencies içerisinde implementation satırlarının altına aşağıdaki gibi firebase analytics kütüphanesini ekleyelim:

implementation platform('com.google.firebase:firebase-bom:27.0.0')
implementation 'com.google.firebase:firebase-analytics'

Daha sonra Android Studio’da üstte Sync Now seçeneği çıkacaktır. Tıklayarak projeyi gradle ile senkronize ediniz.

4. Run your app to verify installation kısmında uygulamayı çalıştırarak Firebase Analytics’in kurulumunu doğrulamamız gerekiyor. Aşağıdaki komutla çalıştırarak “Congratulations” kısmının aktif hale gelmesini sağlayabilirsiniz:

yarn run android

App.tsx tarafında değişikliklerin yapılması

Şimdi kullandığımız cihaz için Firebase token’ı almak amacıyla App.tsx dosyasını açalım ve aşağıdaki gibi değiştirelim:

import React, {useEffect} from 'react';
import firebase from '@react-native-firebase/app';
import messaging from '@react-native-firebase/messaging';
const App = () => {
useEffect(() => {
messaging()
.getToken(firebase.app().options.messagingSenderId)
.then(x => console.log(x))
.catch(e => console.log(e));
}, []);
return <></>;
};
export default App;

Projeyi aşağıdaki gibi çalıştıralım:

yarn android

Proje çalıştığında Metro bundler terminalinde uygulamanın token’ını göreceksiniz.

Not: Bu token’ı push notification’ı test olarak atarken kullanacağız.

Uygulama açık iken push notification geldiğinde bu bildirimin görüntülenmesi için App.tsx’i aşağıdaki hale getirelim:

import React, {useEffect} from 'react';
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
import {Platform} from 'react-native';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import {FirebaseMessagingTypes} from '@react-native-firebase/messaging';
const App = () => {
useEffect(() => {
firebase.messaging().onMessage(response => {
console.log(JSON.stringify(response));
if (Platform.OS !== 'ios') {
showNotification(response.notification!);
return;
}
PushNotificationIOS.requestPermissions().then(() =>
showNotification(response.notification!),
);
});
}, []);
const showNotification = (
notification: FirebaseMessagingTypes.Notification,
) => {
PushNotification.localNotification({
title: notification.title,
message: notification.body!,
});
};
return <></>;
};
export default App;

Şimdi Firebase konsoluna geri dönelim ve solda Grow bölümünün altındaki Cloud Messaging kısmına tıklayarak çıkan ekranda Send your first message butonuna tıklayalım:

  1. Notification bölümünde bildiriminiz ile ilgili bilgileri girebilirsiniz. Bildirim görselini yüklemek için Firebase’deki ücretli plana sahip olmanız gereklidir. Test görselini unsplash’ten edinebirsiniz.

Send test message kısmına tıkladığınızda daha önce terminalde yazan token’ı buraya yapıştırarak, oluşturduğunuz bildirimi kendi cihazınızda test edebilirsiniz:

Telefonunuza aşağıdaki gibi gelecektir:

Diğer ayarlamaları da yapıp Review kısmına tıkladığınızda oluşturduğunuz bildirim ile ilgili özet karşınıza görüntülenecektir. Publish dediğinizde artık bildirim tüm telefonlara iletilecektir.

iOS tarafı için değişikliklerin yapılması

XCode ile projeyi açalım:

open ios/SampleRNPushNotifications.xcworkspace

Daha sonra firebase console’da ios uygulaması ekleme kısmına tıklayalım ve adımları sıra ile takip edelim.

  1. Register app: XCode’da General bölümünde bulunan bundleID kısmını buraya yazalım:

2. Download config file: Dosyayı indirelim ve SampleRNPushNotifications dizininin içine sürükleyelim. Target olarak 4'ünü de seçelim:

3. Add firebase SDK: Podfile dosyamız olduğu için sadece aşağıdaki satırı PodFile dosyasına eklememiz yeterli olacaktır:

pod 'Firebase/Analytics'

Cocoapod’ları yükleyelim:

pod install --project-directory=ios/

4. Add initialization code: AppDelegate.m dosyasında Firebase’i import edelim:

@import Firebase;

didFinishLaunchingOptions fonksiyonu içerisine aşağıdaki satırı ekleyelim:

[FIRApp configure];

5. Run your app to verify installation: Burada uygulamayı çalıştıralım ve firebase ile iletişimde olduğunu görelim:

npx react-native run-ios

App.tsx’te değişikliklerin yapılması

Eğer bendeki gibi iOS simulator kullanıyorsanız aşağıdaki gibi bir uyarı alabilirsiniz. Bu nedenle iOS kodları için test yapamadığımdan dolayı söz veremeyeceğim. Gerekli talimatları buradan edinebilirsiniz. Sertifikalar ve xCode üzerinde ayarlamalar için ise buradan yararlanabilirsiniz. Ayrıca Enes Ozturk ‘ün de React Native iOS için Push Notification Gönderimi hakkında bir yazısı var. İncelemenizi öneririm.

App.tsx’in son hali aşağıdaki gibi olacaktır:

import React, {useEffect} from 'react';
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
import {Platform} from 'react-native';
import {FirebaseMessagingTypes} from '@react-native-firebase/messaging';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
const App = () => {
const getToken = () => {
firebase
.messaging()
.getToken(firebase.app().options.messagingSenderId)
.then(x => console.log(x))
.catch(e => console.log(e));
};
const registerForRemoteMessages = () => {
firebase
.messaging()
.registerDeviceForRemoteMessages()
.then(() => {
console.log('Registered');
requestPermissions();
})
.catch(e => console.log(e));
};
const requestPermissions = () => {
firebase
.messaging()
.requestPermission()
.then((status: FirebaseMessagingTypes.AuthorizationStatus) => {
if (status === 1) {
console.log('Authorized');
onMessage();
} else {
console.log('Not authorized');
}
})
.catch(e => console.log(e));
};
const onMessage = () => {
firebase.messaging().onMessage(response => {
showNotification(response.data!.notification);
});
};
const showNotification = (notification: any) => {
console.log('Showing notification');
console.log(JSON.stringify(notification));
PushNotification.localNotification({
title: notification.title,
message: notification.body!,
});
};
getToken();
if (Platform.OS === 'ios') {
registerForRemoteMessages();
} else {
onMessage();
}
return <></>;
};
export default App;

Sonuç olarak

Push notification olayı rnfirebase ile oldukça kolay hale gelmiş. iOS test aşaması için ise kesinlikle fiziksel bir cihaza ihtiyaç var.

Ayrıca https://github.com/mikehardy/rnfbdemo reposu ile Firebase uyumlu bir React Native projesi üretebilirsiniz. Tek yapmanız gereken ‘com.rnfbdemo’ id’si için bir uygulama oluşturup, proje içine google services plist ve json dosyalarını koymak. Gerisini make-demo.sh dosyası hallediyor.

Projenin bitmiş halini react-native-push-notification-firebase reposunda bulabilirsiniz. Bu yazı hakkında soru ve görüşlerinizi aşağıdaki yorumlar kısmından yazabilirsiniz. Bana destek vermek için alkış simgesine tıklayabilirsiniz. Sonraki yazımda görüşmek üzere…

--

--