PWA (Progressive Web Apps) 은 네이티브 앱과 같은 사용경험을 제공해주는 웹앱이다.
PWA 에서 제공하는 기능 중 가장 궁금했던 기능이 바로 네이티브 앱처럼 Push 알림을 받는것. Google FCM 을 통해서 웹 앱에 알림을 보내는 것을 간단하게 해보자.
웹앱에 대해 초보인 경우 Flutter (open-source UI software development kit) 를 사용하면 좋다.
1) Flutter 설치
Mac OS 가이드
https://docs.flutter.dev/get-started/install/macos/web
- OS: macOS11 (Big Sur) 이상
- default shell: zsh
- 개발 Tool: Google Chrome, Git
- IDE 는 Visual Studio Code , Android Studio , IntelliJ IDEA 중에 편한것으로,
VS Code 는 Flutter 설치까지 쉽게 되기 때문에 VS Code 에서 시작
- Command Palette (Command + Shift + P)> Flutter: New Project 로 프로젝트 생성 (pwa_test)
- Download SDK 팝업이 뜨면 click 해서 설치.
- Select Folder for Flutter SDK Flutter SDK 설치 위치는 원하는곳으로 지정.
- Clone Fltter
- VS Code 재시작
2) Flutter 앱에 Firebase 연동하기
2-1) Firebase 에서 프로젝트 생성
모든 설정은 default 값 유지해서 생성
2-2) Flutter 앱에 Firebase 추가
Flutter 앱에 Firebase 추가
의견 보내기 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. Flutter 앱에 Firebase 추가 plat_ios plat_android plat_web iOS+ Android 웹 기본 요건 아직 Flutter 앱이 없다면
firebase.google.com
$ firebase login # 프로젝트 생성한 구글계정 로그인
$ dart pub global activate flutterfire_cli # FlutterFire CLI 설치
Package flutterfire_cli is currently active at version 1.1.0.
Downloading packages... .
The package flutterfire_cli is already activated at newest available version.
To recompile executables, first run `dart pub global deactivate flutterfire_cli`.
Installed executable flutterfire.
Activated flutterfire_cli 1.1.0.
flutterfire configure 를 실행하면
✔️ 연결할 firebase 프로젝트 선택
✔️ Flutter 앱에서 지원되는 플랫폼 선택 (e.g. web)
$ flutterfire configure
i Found 16 Firebase projects.
✔ Select a Firebase project to configure your Flutter application with · pwa-push-b77e3 (pwa push)
✔ Which platforms should your configuration support (use arrow keys & space to select)? · web
i Firebase web app pwa_test (web) is not registered on Firebase project pwa-push-b77e3.
i Registered a new Firebase web app on Firebase project pwa-push-b77e3.
Firebase configuration file lib/firebase_options.dart generated successfully with the following Firebase apps:
Platform Firebase App Id
web xxxxx
Learn more about using this file and next steps from the documentation:
> https://firebase.google.com/docs/flutter/setup
✔️ Firebase 구성 파일 생성
- lib/firebase_options.dart
- firebase.json
✅ Firebase Console 에 확인해보면 앱이 추가된것 확인
2-3) 연동을 위한 Firebase Core 플러그인 설치
$ flutter pub add firebase_core
Resolving dependencies...
Downloading packages...
async 2.12.0 (2.13.0 available)
fake_async 1.3.2 (1.3.3 available)
+ firebase_core 3.13.0
+ firebase_core_platform_interface 5.4.0
+ firebase_core_web 2.22.0
+ flutter_web_plugins 0.0.0 from sdk flutter
leak_tracker 10.0.8 (10.0.9 available)
material_color_utilities 0.11.1 (0.12.0 available)
+ plugin_platform_interface 2.1.8
vm_service 14.3.1 (15.0.0 available)
+ web 1.1.1
Changed 6 dependencies!
5 packages have newer versions incompatible with dependency constraints.
Try `flutter pub outdated` for more information.
2-4) main.dart 코드에 firebase 초기화 코드 추가
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
2-5) Flutter 웹앱 실행
$ flutter run
Connected devices:
...
No wireless devices were found.
[1]: macOS (macos)
[2]: Mac Designed for iPad (mac-designed-for-ipad)
[3]: Chrome (chrome)
Please choose one (or "q" to quit): 3
Launching lib/main.dart on Chrome in debug mode...
✅ 에러 없이 웹앱 실행
3) Flutter 앱에 Firebase Cloud Messaging 연동하기
3-1) Firebase Messaging Plugin 설치
$ flutter pub add firebase_messaging
Resolving dependencies...
Downloading packages...
+ _flutterfire_internals 1.3.54
async 2.12.0 (2.13.0 available)
fake_async 1.3.2 (1.3.3 available)
+ firebase_messaging 15.2.5
+ firebase_messaging_platform_interface 4.6.5
+ firebase_messaging_web 3.10.5
leak_tracker 10.0.8 (10.0.9 available)
material_color_utilities 0.11.1 (0.12.0 available)
vm_service 14.3.1 (15.0.0 available)
Changed 4 dependencies!
5 packages have newer versions incompatible with dependency constraints.
Try `flutter pub outdated` for more information.
$ flutterfire configure
✔ You have an existing `firebase.json` file and possibly already configured your project for Firebase.
Would you prefer to reuse the values in your existing `firebase.json` file to configure your project? · yes
3-2) Firebase Messaging Code 를 main.dart 에 추가
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
if (await FirebaseMessaging.instance.isSupported()) {
await FirebaseMessaging.instance.setAutoInitEnabled(true);
}
runApp(const MyApp());
}
...
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final FirebaseMessaging _messaging = FirebaseMessaging.instance; ✅
String? _fcmToken;
@override
void initState() {
super.initState();
setupFCM(); ✅
}
void setupFCM() async {
_fcmToken = await _messaging.getToken();
print("🔔 FCM Token: $_fcmToken");
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('📲 Message in foreground: ${message.notification?.title}');
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(message.notification?.title ?? ''),
content: Text(message.notification?.body ?? ''),
),
);
});
}
...
}
✅ 앱 실행 시 알림 허용 팝업 생성
허용시, 해당 앱의 FCM Token 발행
4) Push 테스트
기존 FCM API에서 HTTP v1로 이전 | Firebase Cloud Messaging
Cloud Next 2025에서 Firebase의 최신 소식을 확인하세요. 자세히 알아보기 의견 보내기 기존 FCM API에서 HTTP v1로 이전 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세
firebase.google.com
4-1) 서비스 계정 생성
Firebase 콘솔 > 프로젝트 설정 > 서비스 계정에서 새 비공개키 생성
json 파일을 service-account-file.json 으로 저장하여 사용
$ export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
4-2) python 으로 push 테스트
샘플예제 참고: https://github.com/firebase/quickstart-python
GitHub - firebase/quickstart-python
Contribute to firebase/quickstart-python development by creating an account on GitHub.
github.com
PROJECT_ID = 'pwa-push-b77e3'
BASE_URL = 'https://fcm.googleapis.com'
FCM_ENDPOINT = 'v1/projects/' + PROJECT_ID + '/messages:send'
FCM_URL = BASE_URL + '/' + FCM_ENDPOINT
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
if __name__ == '__main__':
# [Generate push message]
common_message = {
'message': {
# flutter app token
"token": "--------------",
"notification": {
"body": "This is an FCM notification message!",
"title": "FCM Message"
}
}
}
# [Get access_token]
credentials = service_account.Credentials.from_service_account_file(os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"), scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
headers = {
'Authorization': 'Bearer ' + credentials.token,
'Content-Type': 'application/json; UTF-8',
}
# [Send push message]
resp = requests.post(FCM_URL, data=json.dumps(common_message), headers=headers)
✅ flutter web app 으로 push 메세지 전송
'자습' 카테고리의 다른 글
AWS ASG lifecycle Hook (remotely run shell command on EC2) (0) | 2024.03.29 |
---|---|
AWS EC2 X-Ray Enable (0) | 2024.02.24 |
Go Thread-Safety : sync.Mutex, sync.Map (0) | 2023.08.26 |
Spring Native (0) | 2022.05.14 |
go gRPC Server & gRPC Gateway (0) | 2021.09.20 |