o. 노드 패키지 다운
npm i @react-native-firebase/analytics @react-native-firebase/app @react-native-firebase/messaging
npm i react-native-push-notification @react-native-community/push-notification-ios
npm i -D @types/react-native-push-notification
npx pod-install
buildscript {
repositories {
google() //요거
}
dependencies {
classpath 'com.google.gms:google-services:4.3.10'//요거
}
}
allprojects {
repositories {
google() //요거
}
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'//요거
dependencies {
implementation platform('com.google.firebase:firebase-bom:30.0.1')//요거
implementation 'com.google.firebase:firebase-analytics'//요거
}
fooddeliveryapp-da18e-firebase-adminsdk-lp6nt-38f98578d8.json
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
제로초 강의는 조금 다르다. 다음을 복붙한다. (databaseURL의 주소 내용중fooddeliveryapp-6609a는 GOOGLE_APPLICATION_CREDENTIALS의 이름에서 나온다. 반드시 동일하게 해야한다.)
process.env.GOOGLE_APPLICATION_CREDENTIALS =
"./fooddeliveryapp-6609a-firebase-adminsdk-nev9a-603a8b9ae6.json";
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://fooddeliveryapp-6609a.firebaseio.com",
});
FileInputStream serviceAccount =
new FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
FirebaseApp.initializeApp(options);
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="false"/>
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#FFF</color>
</resources>
@Override
public void onNewIntent(Intent intent) {
...
super.onNewIntent(intent);
...
}
설정 끝
이제 프론트에서 푸쉬를 보내보자
import messaging from '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
PushNotification.configure({
// (optional) 토큰이 생성될 때 실행됨(토큰을 서버에 등록할 때 쓸 수 있음)
onRegister: function (token: any) {
console.log('TOKEN:', token);
},
// (required) 리모트 노티를 수신하거나, 열었거나 로컬 노티를 열었을 때 실행
onNotification: function (notification: any) {
console.log('NOTIFICATION:', notification);
if (notification.channelId === 'riders') {
// if (notification.message || notification.data.message) {
// store.dispatch(
// userSlice.actions.showPushPopup(
// notification.message || notification.data.message,
// ),
// );
// }
}
// process the notification
// (required) 리모트 노티를 수신하거나, 열었거나 로컬 노티를 열었을 때 실행
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) 등록한 액션을 누렀고 invokeApp이 false 상태일 때 실행됨, true면 onNotification이 실행됨 (Android)
onAction: function (notification: any) {
console.log('ACTION:', notification.action);
console.log('NOTIFICATION:', notification);
// process the action
},
// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
onRegistrationError: function (err: Error) {
console.error(err.message, err);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
* - if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === 'ios'
*/
requestPermissions: true,
});
PushNotification.createChannel(
{
channelId: 'riders', // (required)
channelName: '앱 전반', // (required)
channelDescription: '앱 실행하는 알림', // (optional) default: undefined.
soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
importance: 4, // (optional) default: 4. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
},
(created: boolean) =>
console.log(`createChannel riders returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
);
// 토큰 설정
import messaging from '@react-native-firebase/messaging';
useEffect(() => {
async function getToken() {
try {
if (!messaging().isDeviceRegisteredForRemoteMessages) {
await messaging().registerDeviceForRemoteMessages();
}
const token = await messaging().getToken();
console.log('phone token', token);
dispatch(userSlice.actions.setPhoneToken(token));
return axios.post(`${Config.API_URL}/phonetoken`, {token});
} catch (error) {
console.error(error);
}
}
getToken();
}, [dispatch]);
const initialState = {
name: '',
email: '',
accessToken: '',
phoneToken:'',
};
...
setPhoneToken:(state, action)=> {
state.phoneToken = action.payload.phoneToken;
}
adb devices
/Users/timothy/project/RN/f2/FoodDeliveryApp/android/app/src/main/AndroidManifest.xml Error:
android:exported needs to be explicitly specified for <receiver>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
성공 연결완료
await axios.post(`${Config.API_URL}/user`, {
email,
password,
name
}, {
headers: {
'Content-Type': 'application/json'
}
})