[swift] Swift에서 로컬 알림의 메시지에 사용자 정보를 동적으로 추가하는 방법

로컬 알림은 사용자에게 중요한 정보를 전달하는 데 유용한 기능입니다. Swift에서 이러한 로컬 알림의 메시지에 사용자 정보를 동적으로 추가하는 방법은 다음과 같습니다.

1. 사용자 정보를 포함한 메시지 문자열 생성

로컬 알림의 메시지에 사용자 정보를 동적으로 추가하기 위해, 사용자 정보를 포함한 메시지 문자열을 생성해야 합니다. 예를 들어, “안녕하세요 {사용자 이름}님, 오늘은 {날짜}입니다.”와 같은 형식으로 메시지 문자열을 생성할 수 있습니다.

let username = "John" // 사용자 이름
let currentDate = Date() // 현재 날짜

let formatter = DateFormatter()
formatter.dateFormat = "yyyy년 MM월 dd일"
let dateString = formatter.string(from: currentDate) // 현재 날짜를 문자열로 변환

let message = "안녕하세요 \(username)님, 오늘은 \(dateString)입니다."

2. 로컬 알림 생성 및 메시지 할당

다음으로, 로컬 알림을 생성하고 앞에서 생성한 메시지를 할당해야 합니다. 로컬 알림은 UNMutableNotificationContent 객체를 사용하여 생성할 수 있습니다.

import UserNotifications

let content = UNMutableNotificationContent()
content.title = "로컬 알림"
content.body = message

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false) // 3초 후 알림을 트리거
let request = UNNotificationRequest(identifier: "NotificationIdentifier", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
    if error != nil {
        print("로컬 알림 등록 실패: \(error!.localizedDescription)")
    }
}

위의 코드에서 message는 앞에서 생성한 사용자 정보를 포함한 메시지 문자열입니다. 그리고 UNTimeIntervalNotificationTrigger는 알림을 트리거할 시간 간격을 설정합니다. 이 예제에서는 3초 후에 알림이 트리거됩니다.

참고자료