Geon

iOS 앱에서 로컬 푸시 알림(Local Push Notification)을 구현하는 방법은 무엇인가요? 본문

iOS developer essential skills

iOS 앱에서 로컬 푸시 알림(Local Push Notification)을 구현하는 방법은 무엇인가요?

jgkim1008 2024. 6. 24. 15:09

로컬 푸시 알림과 원격 푸시 알림(Remote Push Notification)의 차이점은 무엇인가요?

로컬 푸시 알림 (Local Push Notification)

  • 로컬 푸시 알림은 앱이 실행 중이거나 백그라운드에서 로컬 데이터에 기반하여 알림을 생성하고 표시하는 방식
  • 로컬 푸시 알림은 서버와의 통신이 필요 없으며, 주로 사용자의 기기 내에서 발생하는 이벤트나 일정에 따라 알림을 생성합니다.
  • 사용 사례:
    • 일정 알림: 캘린더 앱에서 사용자의 일정에 따라 알림을 설정.
    • 타이머 또는 알람: 시간 경과에 따라 알림을 표시.
    • 위치 기반 알림: 사용자가 특정 위치에 도달했을 때 알림을 트리거.

원격 푸시 알림 (Remote Push Notification)

  • 원격 푸시 알림은 서버에서 생성되어 푸시 알림 서비스를 통해 사용자의 기기로 전달되는 알림이며 이 방식은 서버와의 통신이 필요

  • 앱이 실행 중이 아니더라도 알림을 전송할 수 있습니다.

  • 로컬 노티 전송 방법

import UserNotifications  
import SwiftUI


@main  
struct ContentView: View {
    var body: some View { VStack { Text("test") } } .onAppear { scheduleLocalNotification() }


func scheduleLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "Time to Check the App"
    content.body = "It's time to see what's new!"
    content.sound = .default

// Trigger after 10 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)

let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)

      UNUserNotificationCenter.current().add(request) { error in
          if let error = error {
              print("Error scheduling local notification: \(error)")
          }
      }
  }
}
  • 원격 푸시 알림
    • 아래 페이지 참고

푸시 알림의 콘텐츠(Content)와 트리거(Trigger)는 어떤 역할을 하나요?

  • 컨텐츠
    • 컨텐츠는 말 그대로 노티피케이션에 보여줄 컨텐츠
    • 상단 코드 예시를 보면 title, body, sound, badge 를 설정할수 있다.
  • 트리거
    • 말 그대로 트리거 몇초뒤에, 반복 여부 등 을 설정할수 있다.
  • request
    • 위 컨텐츠와 트리거를 합하여 UNNotificationRequest를 보낸다.

사용자가 푸시 알림을 탭했을 때 앱의 동작을 처리하는 방법을 설명해주세요.

- UNUserNotificationCenterDelegate 의 delegate 메서드를 통해 처리하면 된다.

extension AppDelegate: UNUserNotificationCenterDelegate {

// Foreground에서 알림을 수신했을 때
func userNotificationCenter(_ center: UNUserNotificationCenter,
                          willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    completionHandler([.alert, .badge, .sound])
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
            if UIApplication.shared.applicationState == .active || UIApplication.shared.applicationState ==                 .inactive { // 앱이 켜져있는 상태에서 클릭시 (활성화/비활성화(잠깐 숨겨놓은 상태))
                  } else { // 앱이 꺼져있는 상태에서 클릭시 (백그라운드)

                }
                completionHandler()
  }
}