[swift] Swift에서 로컬 알림의 반복 설정하는 방법

로컬 알림은 iOS 애플리케이션에서 중요한 사용자 알림을 제공하기 위해 사용됩니다. 반복적으로 발생하는 알림을 설정하려면 Swift에서 다음과 같은 단계를 따릅니다.

  1. 먼저 UserNotificationCenter를 가져옵니다.
import UserNotifications
  1. UNUserNotificationCenter.current()를 사용하여 현재 UserNotificationCenter 객체에 액세스합니다.
let center = UNUserNotificationCenter.current()
  1. 알림에 사용할 UNNotificationContent 객체를 생성합니다. 이 객체에는 알림의 제목, 내용, 사운드 등이 포함됩니다.
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "Don't forget to do your task!"
content.sound = UNNotificationSound.default
  1. 알림의 반복 설정을 구성하는 UNCalendarNotificationTrigger 객체를 생성합니다. 이 객체에는 반복할 시간 및 날짜 정보가 포함됩니다.
let dateComponents = DateComponents(hour: 9, minute: 0, weekday: 1)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

위의 예는 매주 월요일 오전 9시에 알림이 반복되도록 설정한 것입니다.

  1. UNNotificationRequest 객체를 생성하여 이전 단계에서 생성한 contenttrigger를 포함시킵니다.
let request = UNNotificationRequest(identifier: "repeatingNotification", content: content, trigger: trigger)
  1. UserNotificationCenter에 알림 요청을 추가합니다.
center.add(request) { (error) in
    // 알림 요청 추가 완료 시 실행될 코드
}

이제 앱을 실행하면 매주 월요일 오전 9시에 반복적으로 알림이 표시됩니다.

참고 자료: