[swift] Swift에서 로컬 알림을 특정 시간 간격마다 발생시키는 방법

iOS 애플리케이션에서 로컬 알림을 사용하여 사용자에게 특정 시간 간격마다 알림을 보내고 싶다면, Swift의 UserNotifications 프레임워크를 활용할 수 있습니다. 이 프레임워크를 사용하여 로컬 알림을 예약 및 발생시킬 수 있습니다.

다음은 로컬 알림을 1분마다 발생시키는 예제 코드입니다.

import UserNotifications

class NotificationManager {
    
    static let shared = NotificationManager()
    
    private init() {}
    
    func scheduleNotification() {
        let content = UNMutableNotificationContent()
        content.title = "알림 제목"
        content.body = "알림 내용"
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
        
        let request = UNNotificationRequest(identifier: "notificationIdentifier", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("알림 예약에 실패했습니다: \(error.localizedDescription)")
            } else {
                print("알림이 예약되었습니다.")
            }
        }
    }
}

위 코드는 NotificationManager 라는 싱글톤 클래스를 정의하고, scheduleNotification 메서드를 통해 로컬 알림을 예약하고 발생시킵니다. content 객체는 알림의 제목과 내용을 설정하고, trigger 객체는 알림을 발생시킬 시간 간격을 설정합니다. 위 코드에서는 1분마다 알림이 발생하도록 설정되어 있습니다.

알림을 예약하기 위해 UNUserNotificationCenter.current().add(request) 메서드를 호출하면 알림이 예약되고, 클로저를 통해 성공 또는 실패 여부를 확인할 수 있습니다.

위 코드를 실행하면 앱이 백그라운드 또는 종료된 상태에서도 알림이 발생하며, 사용자에게 알림이 표시됩니다.

반복적으로 알림을 예약하고 발생시키기 위해서는 UNTimeIntervalNotificationTrigger 대신 UNCalendarNotificationTriggerUNLocationNotificationTrigger 등의 트리거 유형을 활용할 수도 있습니다. 필요에 따라 사용하면 됩니다.

더 자세한 내용은 Apple Developer Documentation을 참조하시기 바랍니다.