본문 바로가기

아카이브/Flutter

[FCM] Firebase Cloud Messaging 설정

1. 프로젝트 생성

  • Command +. Shift + p
  • Flutter: New Application Project

새 프로젝트 생성

 

2. 패키지 주소 확인 및 변경

  • flutter 프로젝트에서 com.example.project_name
  • ios/Runner -> Xcode com.example.projectName
    • Target -> Runner -> Signing의 팀도 확인

 

3. Firebase 프로젝트 생성

프로젝트 추가

 

4. 안드로이드 앱 등록

  • Firebase 프로젝트에 안드로이드 앱 등록

앱 추가
안드로이드 추가

  • <project>/android/app  google-services.json 이동

<project>/android/app 폴더에 구성 파일 추가

 

  • <project>/build.gradle
buildscript {
  ext.kotlin_version = '1.3.50'
  repositories {
      google() // 없으면 추가
      jcenter()
  }
​
  dependencies {
      classpath 'com.android.tools.build:gradle:4.1.0'
      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
      classpath 'com.google.gms:google-services:4.3.8' // 추가
  }
   
}
​
allprojects {
  repositories {
      google() // 없으면 추가
      jcenter()
  }
}
​
...

 

  • <project>/<app-module>/build.gradle
...
​
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services' // 추가
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
​
android {
  compileSdkVersion 30
​
  sourceSets {
      main.java.srcDirs += 'src/main/kotlin'
  }
​
  defaultConfig {
      // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
      applicationId "com.leecoder.lotto"
      minSdkVersion 16
      targetSdkVersion 30
      multiDexEnabled true // minSdkVersion 20 이하 일 때 추가,
      versionCode flutterVersionCode.toInteger()
      versionName flutterVersionName
  }
​
  buildTypes {
      release {
          // TODO: Add your own signing config for the release build.
          // Signing with the debug keys for now, so `flutter run --release` works.
          signingConfig signingConfigs.debug
      }
  }
}
​
flutter {
  source '../..'
}
​
dependencies {
  implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
  implementation platform('com.google.firebase:firebase-bom:28.2.1') // 추가
  implementation 'com.android.support:multidex:1.0.3' // minSdkVersion 20 이하 일 때 추가,
}


5. iOS 앱 생성

앱 추가
iOS 추가

  • <project>/ios/Runner로 GoogleService-Info.plist 이동

<project>/ios/Runner 폴더에 구성 파일 추가

  • Xcode, Runner에 GoogleService-Info.plist 등록

Xcode, Runner 폴더에 파일 추가
추가된 GoogleService-Info.plist

6. iOS APN 설정

  • 사전에 애플 개발자 등록이 필요

 

Team ID를 따로 기록해두자

'더하기'를 눌러서 Identifier 추가  
App IDs 선택

 

App 선택
Team ID 선택, 번들 ID, 설명 입력

 

Capabilities, 푸시 알람 선택

 

'더하기'를 눌러서 Certificate 추가 
개발 및 배포용 선택

 

Team ID + 번들 ID 조합의 App ID 선택

 

CSR 파일이 필요

 

런치패드의 키체인 접근
인증서 요청
인증서 디스크에 저장

 

CSR 파일 업로드
Download 시 생성되는 aps.cer 파일 더블 클릭

 

'더하기'를 눌러서 Key 추가

 

  • 키는 최대 2개만 가능하지만, 한개의 키로 여러 앱에서 사용가능하다.

키 이름 입력, APNs 체크 Continue
생성된 Key 파일, 한번만 다운로드 되니 주의

  • 키 업로드

Firebase Console의 진행중인 프로젝트에서 프로젝트 설정
클라우드 메시징 설정
APN 인증 키 업로드
p8 파일 업로드, p8 파일의 AuthKey_ 뒷 부분은 키 ID에, 처음에 기록해둔 Team ID 입력
인증 키 등록 확인

 

7. Xcode Capability 설정

Xcode, + Capability

 

Background Modes(Background fetch, Remote notifications), Push Notifications 추가

 

  1. Flutter에 firebase_messaging 패키지 추가
 

firebase_core | Flutter Package

Flutter plugin for Firebase Core, enabling connecting to multiple Firebase apps.

pub.dev

 

firebase_messaging | Flutter Package

Flutter plugin for Firebase Cloud Messaging, a cross-platform messaging solution that lets you reliably deliver messages on Android and iOS.

pub.dev

 

 

 

pubspec.yaml 에 패키지 추가

 

  • main.dart
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(); 

  print("Handling a background message: ${message.messageId}");
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); //
  await Firebase.initializeApp(); //
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); //
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
  	// 권한 체크
    if (Platform.isIOS) { 
      Future.microtask(() async {
        await FirebaseMessaging.instance
            .requestPermission(
          alert: true,
          announcement: false,
          badge: true,
          carPlay: false,
          criticalAlert: false,
          provisional: false,
          sound: true,
        )
            .then((settings) {
          print('User granted permission: ${settings.authorizationStatus}');
        });
      });
    } 
    // 권한 체크
...

 

 

  • home.dart
...

@override
void initState() {
  super.initState();
  // Firebase

  FirebaseMessaging.instance
      .getInitialMessage()
      .then((RemoteMessage? initialMessage) {
    print('initialMessage data: ${initialMessage?.data}');
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print('onMessageOpenedApp data: ${message.data}');
  });

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print('Got a message whilst in the foreground!');
    print('onMessage data: ${message.data}');

    if (message.notification != null) {
      print('Message also contained a notification: ${message.notification}');
    }
  });

  // Firebase
}

...

 

https://dalgonakit.tistory.com/120
https://eunjin3786.tistory.com/280
https://firebase.flutter.dev/docs/overview
https://firebase.flutter.dev/docs/messaging/overview/
 

Flutter FCM (Firebase Cloud Messaging) 적용부터 사용까지 (Android, iOS)

이번에는 안드로이드와 아이폰을 동시에 Push 지원해 주는 FCM을 연결해보고 직접 푸쉬를 보내는 방법까지 다뤄보겠습니다. 이 강좌를 언제 올릴까....... 고민...... 고민...... 고민........ 하다가 이

dalgonakit.tistory.com

 

[Flutter] Firebase Cloud Messaging 연동 + 파베 콘솔에서 푸쉬보내기

[1] Flutter앱에 Firebase 추가하기 firebase.google.com/docs/flutter/setup?hl=ko 여기 문서를 보고 따라해주세요 그리고 iOS는 안드로이드와 달리 한단계 더 있는데, APN(Apple push notification) 구성을 따..

eunjin3786.tistory.com

 

FlutterFire Overview | FlutterFire

<img< p=""> </img<>

firebase.flutter.dev

 

Firebase Cloud Messaging | FlutterFire

What does it do?

firebase.flutter.dev