[swift] Swift에서 로컬 알림의 메시지 본문에 변수를 넣는 방법

다음은 Swift에서 로컬 알림의 메시지 본문에 변수를 넣는 예제 코드입니다:

import UserNotifications

// 로컬 알림을 생성하고 보내는 함수
func sendLocalNotification() {
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    
    // 변수 값 동적으로 삽입
    let name = "John"
    content.body = "안녕하세요, \(name)님! 알림을 확인해주세요."
    
    // 알림 요청 생성
    let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: nil)
    
    // 알림 요청을 등록
    center.add(request) { (error) in
        if let error = error {
            print("로컬 알림을 보내는 중에 오류가 발생했습니다: \(error.localizedDescription)")
        }
    }
}

위의 코드에서, 우리는 UNMutableNotificationContent 객체를 생성하고, body 프로퍼티에 변수 값을 동적으로 삽입하고 있습니다. 이 예제에서는 name 변수가 “John”으로 설정되었습니다.

실제 알림을 보내려면 UNUserNotificationCenter.current()를 사용하여 알림 센터의 인스턴스를 가져온 다음, UNNotificationRequest 객체를 생성하여 알림을 등록합니다. 이런 식으로 우리는 메시지 본문에 동적인 변수를 삽입하여 로컬 알림을 보낼 수 있습니다.

참고자료: