[swift] Swift에서 로컬 알림을 특정 일정 시간 후에 발생하도록 설정하는 방법

로컬 알림은 Swift 애플리케이션에서 사용자에게 중요한 정보를 알리는 강력한 도구입니다. 이것을 사용하여 특정 일정 시간 후에 알림을 발생시키는 방법을 알아보겠습니다.

1. UserNotifications 프레임워크 임포트

import UserNotifications

2. 로컬 알림 권한 요청

로컬 알림을 사용하기 전에 사용자에게 알림 권한을 요청해야 합니다. 앱이 처음 시작될 때 다음 코드를 추가하여 권한을 요청할 수 있습니다.

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
    // 알림 권한이 허용되었는지 여부 확인
    if granted {
        print("알림 권한이 허용되었습니다.")
    } else {
        print("알림 권한이 거부되었습니다.")
    }
}

3. 로컬 알림 예약

로컬 알림을 예약하려면 다음 단계를 따르세요.

// 알림 콘텐츠 생성
let content = UNMutableNotificationContent()
content.title = "알림 제목"
content.body = "알림 본문"

// 알림 트리거 생성
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60*60, repeats: false)

// 알림 요청 생성
let request = UNNotificationRequest(identifier: "UniqueNotificationID", content: content, trigger: trigger)

// 알림 예약
UNUserNotificationCenter.current().add(request) { (error) in
    if let error = error {
        print("알림 예약 도중 오류 발생: \(error.localizedDescription)")
    } else {
        print("알림이 성공적으로 예약되었습니다.")
    }
}

위의 코드에서 UNTimeIntervalNotificationTrigger 생성자의 timeInterval 매개변수는 예약한 시간을 초 단위로 지정합니다. 위의 예에서는 60분 후에 알림이 발생하도록 설정되어 있습니다.

4. 로컬 알림 취소

예약된 로컬 알림을 취소하려면 다음 코드를 사용하세요.

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["UniqueNotificationID"])

위의 코드에서 "UniqueNotificationID"는 예약한 알림을 식별하는 고유한 식별자입니다.

5. 참고 자료