[swift] Swift에서 로컬 알림을 특정 기간 동안 반복 예약하는 방법

iOS에서 로컬 알림을 사용하여 사용자에게 일정을 알려주는 기능을 구현하려면 반복 예약이 필요할 수 있습니다. Swift를 사용하여 로컬 알림을 특정 기간 동안 반복 예약하는 방법에 대해 알아보겠습니다.

1. UserNotifications 프레임워크 추가

먼저, 프로젝트에 UserNotifications 프레임워크를 추가해야합니다. 프로젝트 네비게이션 창에서 타겟을 선택한 후, Build Phases 탭으로 이동합니다. Link Binary With Libraries 섹션에서 UserNotifications.framework를 추가합니다.

2. 권한 요청

로컬 알림을 사용하기 위해서는 사용자의 권한을 요청해야합니다. AppDelegate.swift 파일을 열고 didFinishLaunchingWithOptions 메서드에 다음 코드를 추가합니다.

import UserNotifications

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
}

3. 로컬 알림 예약

로컬 알림을 반복해서 예약하기 위해 UNMutableNotificationContentUNTimeIntervalNotificationTrigger 클래스를 사용합니다. 특정 기간마다 반복 예약하기 위해 반복 간격을 설정합니다.

import UserNotifications

func scheduleLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "알림 제목"
    content.body = "알림 내용"
    content.sound = UNNotificationSound.default

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

    let request = UNNotificationRequest(identifier: "notificationIdentifier", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request) { (error) in
        if error != nil {
            print("로컬 알림 예약 실패")
        } else {
            print("로컬 알림 예약 성공")
        }
    }
}

위 예제에서는 매일 동일한 시간에 알림이 반복되도록 1일 간격으로 반복 예약하고 있습니다. timeInterval 값을 변경하여 원하는 반복 주기를 설정할 수 있습니다.

4. 예약된 로컬 알림 취소

예약된 로컬 알림을 취소하려면 UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 메서드를 호출하면 됩니다. 예를 들어, 앱이 종료될 때 예약된 알림을 취소하고 싶은 경우 AppDelegate.swift 파일의 applicationDidEnterBackground 메서드에 다음 코드를 추가합니다.

import UserNotifications

func applicationDidEnterBackground(_ application: UIApplication) {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}

위의 예제에서는 앱이 백그라운드에 진입할 때 예약된 알림이 모두 취소되도록 설정하고 있습니다.

이제 Swift에서 로컬 알림을 특정 기간 동안 반복 예약하는 방법에 대해 알게 되었습니다. 자세한 내용은 Apple의 UserNotifications 문서를 참조할 수 있습니다.