대머리개발자

앱 푸시 - FCM 본문

개발이야기/개념

앱 푸시 - FCM

대머리개발자 2024. 11. 27. 17:16
728x90

자세한 내용은 해당 블로그에 확인한다. 너무나도 잘 기록되어있다. ㄳ

https://zuminternet.github.io/FCM-PUSH/

 

FCM 푸시 파헤치기

파일럿부터 적용까지 진행했던 FCM 푸시를 파헤치며 기초 가이드북처럼 정리해보았습니다.

zuminternet.github.io

 

그럼에도 간단하게 설명하자면 PUB / SUB 개념과 동일하다고 생각한다.

https://velog.io/@haron/PUBSUB-PUBSUB%EC%9D%84-%ED%8C%8C%ED%97%A4%EC%B3%90%EB%B3%B4%EC%9E%90

 

 

공급자(Publisher)는 메세지를 만들어는 내는 우리가 되는 것이고

메세지를 소비하는 사용자는 구독자(Subscriber), 즉 클라이언트가 되는 것이다.

 

따라서 공급자에 대한 설정구독자에  대한 설정을 해야 하는 것이다.

 

상대적으로 공급자(서버) 설정이 쉽다.

 

1. 프로젝트 대충 만든다.

2. 프로젝트 설정 -> 서비스 계정으로 접근한다.

3. 비공개 키 생성해서 json 파일 다운로드 받는다.

 

4. 3번째에서 생성된 파일을 바인딩해서 Init 한다.

package com.oauth.common;


import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Service
@RequiredArgsConstructor
public class FcmService {

    private String projectId = "id-53055";
    private String topicName = "topic-53055";

    @PostConstruct
    public void initialize() throws IOException {
        FirebaseOptions options = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(new ClassPathResource("firebase.json").getInputStream()))
                .setProjectId(projectId)
                .build();
        FirebaseApp.initializeApp(options);
    }

    public void sendMessageByTopic(String title, String body) throws FirebaseMessagingException {
        Message message = Message.builder()
                .setNotification(Notification.builder().setTitle(title).setBody(body).build())
                .setTopic(topicName)
                .build();

        FirebaseMessaging.getInstance().send(message);
        System.out.println("FCM message sent successfully to topic: " + topicName);
    }

    public void sendMessageByToken(String title, String body,String token) throws FirebaseMessagingException {
    FirebaseMessaging.getInstance().send(Message.builder()
            .setNotification(Notification.builder()
                    .setTitle(title)
                    .setBody(body)
                    .build())
            .setToken(token)
            .build());
    }
}

 

TODO로 할 것은 Push 이력 관리 정도 있으면 되겠다. 병렬로 조지면 되겠다.^^

 

대충.!! 일단 토픽으로 테스트해봤다.

### PUSH
POST http://localhost/msg
Content-Type: application/json
Authorization: Bearer {{auth}}

{
    "executeEvent" : "PUSH",
    "title" : "야호호호",
    "content" : "[별거] 없다!!"
}

 

토큰..

 

생각보다...쉽게..야호!

 

구독자 설정도 생각 보다..쉽다.

 

1. 프로젝트 설정 -> 일반으로 접근해서 플로터에 대한 앱을 추가 한다.

 

2. 시행착오를 거쳐 본다. 삽질은 그대를 배신하지 않는다.

 

3.  구성이 완료되면 json

 

 

4. 서버와 마찬가지로 Firebase 초기화 해 주고.. 요청이 왔을 때 요청에 대한 알림을 띄어 주면 딱 끝!!!

void main() async{
  
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
      ..
}

..

class _MyAppState extends State<MyApp> {
    @override
    void initState() {
        super.initState();
        FirebaseMessaging.instance.subscribeToTopic('topic-53055'); // 원하는 토픽 이름으로 변경

        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          RemoteNotification? notification = message.notification;
          AndroidNotification? android = message.notification?.android;

          if (notification != null && android != null) {
            flutterLocalNotificationsPlugin.show(
                notification.hashCode,
                notification.title,
                notification.body,
                NotificationDetails(
                  android: AndroidNotificationDetails(
                    channel.id,
                    channel.name,
                    channelDescription: channel.description,
                    icon: 'launch_background',
                  ),
                ));
          }
        });
        ..
    }
}

 

좋았다!

728x90

'개발이야기 > 개념' 카테고리의 다른 글

앱 푸시 - FCM - 조금 고도화  (0) 2025.02.27
1년이 더해지는 날짜 Formatter 이슈  (0) 2025.01.03
flatMap vs map  (1) 2024.11.20
API 호출 vs DB View  (0) 2024.11.11
비트 연산은 생각보다 파워풀한 친구다.  (0) 2024.08.19