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

로컬 알림은 iOS 앱에서 중요한 정보를 사용자에게 전달하는 효과적인 방법입니다. 반복 알림은 특정 시간 간격으로 반복되어 알림을 받을 수 있도록 설정할 수 있습니다. 이번 글에서는 Swift에서 로컬 알림의 반복 간격을 설정하는 방법에 대해 알아보겠습니다.

1. UNTimeIntervalNotificationTrigger 사용

로컬 알림을 반복하는 가장 간단한 방법은 UNTimeIntervalNotificationTrigger 클래스를 사용하는 것입니다. 이 클래스는 특정 시간 간격으로 반복 알림을 설정할 수 있도록 도와줍니다.

먼저, UNTimeIntervalNotificationTrigger 인스턴스를 생성합니다. 그 다음, UNNotificationRequest를 생성하고 이를 UNUserNotificationCenter에 등록합니다. 예를 들면 다음과 같습니다.

import UserNotifications

...

let content = UNMutableNotificationContent()
content.title = "Daily Reminder"
content.body = "Don't forget to drink water!"

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60*60*24, repeats: true)

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

UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("Error adding notification \(error.localizedDescription)")
    } else {
        print("Notification added successfully")
    }
}

위 코드에서는 매일 24시간마다 알림이 반복되는 설정을 하였습니다. UNTimeIntervalNotificationTriggertimeInterval 매개변수는 반복 간격을 초 단위로 설정할 수 있습니다.

2. 달력 기반 알림 설정

UNCalendarNotificationTrigger를 사용하면 달력 기반의 반복 알림을 설정할 수도 있습니다. 예를 들어, 매주 특정 요일과 시간에 알림을 받고 싶다면, 다음과 같이 코드를 작성할 수 있습니다.

import UserNotifications

...

let content = UNMutableNotificationContent()
content.title = "Weekly Reminder"
content.body = "Have a productive week!"

var dateComponents = DateComponents()
dateComponents.weekday = 3 // 수요일
dateComponents.hour = 9

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

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

UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("Error adding notification \(error.localizedDescription)")
    } else {
        print("Notification added successfully")
    }
}

위 코드에서는 매주 수요일 오전 9시에 알림이 반복되도록 설정했습니다. dateComponents의 속성을 조정해서 원하는 요일과 시간을 설정할 수 있습니다.

마무리

이렇게 Swift에서 로컬 알림의 반복 간격을 설정하는 방법에 대해 알아보았습니다. UNTimeIntervalNotificationTriggerUNCalendarNotificationTrigger를 적절히 조합하여 다양한 반복 알림 설정이 가능합니다. 앱 개발 시 유용하게 활용할 수 있는 로컬 알림 기능을 적절하게 활용해보세요!

참고: