꿀똥벌레
꿀똥벌레 개발 블로그
꿀똥벌레
전체 방문자
오늘
어제
  • 분류 전체보기 (90)
    • JAVA (17)
    • SPRING (14)
    • Elasticsearch (4)
    • GRADLE (2)
    • HTML, CSS (0)
    • JAVASCRIPT (0)
    • GIT (1)
    • Vue.js (1)
    • server (1)
    • Python (0)
    • IT리뷰 (0)
    • 인프라 (6)
    • IOS (21)
    • 디자인패턴 (20)
    • Kafka (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 인덱스 템플릿
  • maxConnPerRoute
  • ES
  • java
  • spring
  • 스프링 인테그레이션
  • KEEPALIVE
  • spring integration
  • persistence connection
  • SWIFT
  • elasticsearch
  • mappings
  • springintegration
  • 스프링 인티그레이션
  • Index Template
  • connectionRequestTimeout
  • persistent connection
  • maxConnTotal
  • Index
  • 엘라스틱서치

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
꿀똥벌레

꿀똥벌레 개발 블로그

IOS

iOS fcm을 이용한 remote push 알림

2023. 9. 22. 16:02

기본적인 애플 remote notification 및 구글 fcm설정에 대한 내용은 다루지 않는다.

NotificationCenter

  • NotificationCenter는 이벤트 브로커 같은 역할을 한다.
  • 이벤트를 수신하여 옵저버들에게 발송한다.NotificationCenter.default.post
  • 디폴트 NotificationCenter로 메세지를 보낸다.
  • Notification 구조체를 파라미터로 받는다.
  • 또는 name: NotificationName, object: Any?, userInfo: [AnyHashable: Any?] 를 받는다.
    • 이 파라미터들은 Notification 필드들과 동일하다.

NotificationCenter.default.addObserver

  • name: 수신할 notification의 이름을 지정. 지정하면 해당 name의 notification만을 구독하는 옵저버로 지정된다.
  • object: object를 지정하면, 해당 object가 지정한 알림만을 observer가 수신한다.
  • queue: 블록이 실행되는 작업 큐이다.
  • using: 옵저버 블록, subscribe하여 진행할 작업을 정의한다.

UNUserNotificationCenter

  • 알림과 관련된 작업을 관장하는 오브젝트
  • 로컬에서 보내는 알림 혹은 원격에서 보내는 알림(푸쉬알림, 뱃지, 사운드) 과 관련된 설정들을 관장한다.

UNUserNotificationCenterDelegate

  • 알림을 수신 할때를 핸들링 하는 딜리게이트 프로토콜
  • 해당 딜리게이트를 구현하여 willPresent, didReceive 에대한 작업을 구현할 수 있다.사용
  • 알림, 사운드, 뱃지의 권한 요청시
  • actionable 알림 (버튼을 출력하는 등의 알림)에 대한 작업을 정의 혹은 선언할 때
  • 알림 예약 처리 할때
  • apns를 통한 원격 알림 처리를 할때
  • 이미 전달 된 알림을 관리할 때
  • 앱의 알림 관련 세팅을 할때

remote notification with FCM

1. 해당 디바이스의 앱이 remote notification 을 받을 수 있도록 apns에 등록

UIApplication.shared.registerForRemoteNotifications()

apns에 정상적으로 해당 디바이스가 등록되거나 실패하면, 토큰과 함께 아래 메소드가 콜백으로 실행된다.

//성공
UIApplicationDelegate#application(_:didRegisterForRemoteNotificationsWithDeviceToken:)
//실패
UIApplicationDelegate#application(_:didFailToRegisterForRemoteNotificationsWithError:)

권한 허용 여부 체크는 아래 메소드로 확인 가능하다.

UNUserNotificationCenter.current().getNotificationSettings(completionHandler:)

2. 사용자에게 푸쉬, 뱃지, 사운드 권한 요청

let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { granted, error in
  if let error {
    print(error)
  }
}
  • 해당 메소드를 실행하면 유저에게 권한 요청 알림이 표출 된다.
  • 권한을 허용한 경우 granted = true 로 콜백이 실행 된다.
  • 권한을 허용하지 않았거나, 아직 결정되지 않은 경우 granted = false 로 콜백이 실행 된다.
  • 이후의 반복 실행의 경우 권한 요청 알림이 표출되지 않고, completionHandler 블록만이 실행 된다.
  • 권한을 허용하지 않은 유저가 이후에 앱 세팅 설정을 통해 권한 수정을 할 수 있도록 UNUserNotificationCenter.current().getNotificationSettings(completionHandler:) 메소드를 사용하거나 할 수 있다.

3. 알림 수신시 핸들링 메소드 구현

extension MyAppDelegate: UNUserNotificationCenterDelegate {

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.banner, .sound, .badge])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) {
  }

}

4. fcm 설정

FirebaseApp.configure()

FirebaseApp shared instance를 설정 해 준다.

5. fcm registration 토큰 받아오기

FCM sdk는 앱이 시작될 때 fcm토큰을 생성한다. 생성된 토큰은 MessagingDelegate#messaging(messaging:didReceiveRegistrationToken:) 로 수신 한다.
앱 최초 실행, 토큰이 업데이트 되거나 비활성화 되는 경우에 콜백이 실행된다.
fcm registration 토큰은 다음과 같은 경우 새로 로딩 된다.

  • 새 기기에서 앱 복원
  • 사용자가 앱 제거/재설치
  • 사용자가 앱 데이터 삭제
    Messaging.messaging().token(completion:) 을 통해 즉시 토큰을 가지고 올 수 있다.

6. fcm과 apns토큰 매핑

UIApplicationDelegate#application(_ application:didRegisterForRemoteNotificationsWithDeviceToken deviceToken:) 메소드내에서
Messaging.messaging().apnsToken = deviceToken 을 실행하여 앱 실행 시 생성된 fcm토큰과 실제 remote push 에사용되는 apns토큰을 매핑한다.

7. 앱이 떠있을 때의 푸쉬 알림에 대해 기능 정의

UNUserNotificationCenterDelegate#userNotificationCenter(center:, willPresent notification:, withCompletionHandler completionHandler:) 메소드 에서

completionHandler([.banner, .sound, .badge])

를 실행해 준다.

8. fcm 토큰 자동 생성 disabled처리

자동으로 fcm 토큰을 생성하는 게 아니라 유저 동의를 받고 생성하려면
info.plist 에 FirebaseMessagingAutoInitEnabled = NO 로 설정하고,
필요할 때 런타임에 Messaging.messaging().autoInitEnabled = true 를 실행 한다.

 

참고
애플 공식 문서
firebase 문서
fcm 문서
https://silver-g-0114.tistory.com/106

저작자표시 (새창열림)

'IOS' 카테고리의 다른 글

UIKit 스토리 보드 없이 프로젝트 시작하기  (0) 2024.02.25
Swift Combine 알아 보기  (1) 2023.12.18
SwiftUI onDelete 수정자 사용  (0) 2023.02.25
SwiftUI ViewBuilder란  (0) 2023.02.17
Swift GCD  (0) 2023.02.02
    꿀똥벌레
    꿀똥벌레
    개발자 꿀똥벌레 입니다.

    티스토리툴바