[swift] Swift에서 로컬 알림을 특정 주기로 반복하는 방법

로컬 알림은 사용자에게 특정 시간에 메시지를 보내거나 알림을 전달하는 데 사용되는 기능입니다. Swift에서 로컬 알림을 특정 주기로 반복하려면 구성과 예약 단계를 거쳐야 합니다.

  1. 알림 센터 권한 요청 로컬 알림을 사용하려면 앱이 알림 센터에 액세스할 수 있는 권한을 가지고 있어야 합니다. 알림 센터 권한을 요청하려면 AppDelegate.swift 파일의 didFinishLaunchingWithOptions 메서드에 다음 코드를 추가하세요.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   // 알림 센터 권한 요청
   UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
      if granted {
         print("알림 권한이 허용되었습니다.")
      } else {
         print("알림 권한이 거부되었습니다.")
      }
   }
   return true
}
  1. 반복 로컬 알림 설정 반복 로컬 알림을 설정하려면 UNMutableNotificationContent와 UNTimeIntervalNotificationTrigger를 사용해야 합니다. 예를 들어, 매일 같은 시간에 알림을 보내고 싶다면 다음 코드를 사용하세요.
// 로컬 알림 센터 생성
let center = UNUserNotificationCenter.current()

// 반복 알림 내용 설정
let content = UNMutableNotificationContent()
content.title = "매일 알림"
content.body = "매일 같은 시간에 알림을 받습니다."

// 알림 시간 설정
var dateComponent = DateComponents()
dateComponent.hour = 9
dateComponent.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)

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

// 알림 센터에 요청 추가
center.add(request) { (error) in
   if let error = error {
      print("알림 요청 추가 중 에러 발생: \(error.localizedDescription)")
   }
}

위 코드는 매일 9시에 알림을 보내는 예제입니다. 주기적으로 알림을 보내고 싶은 경우에는 dateComponent의 hour 및 minute 값을 변경하여 설정할 수 있습니다.

이제 Swift에서 로컬 알림을 특정 주기로 반복하는 방법을 알게 되었습니다. 위의 예제 코드를 참고하여 앱에 맞게 로컬 알림을 구성하세요. 추가적인 제어 및 사용자 지정을 위해 UNNotificationAction, UNNotificationCategory 등의 개념도 알아보세요. 자세한 내용은 Apple 개발 문서를 참조하시기 바랍니다.