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

로컬 알림은 앱 사용자들에게 중요한 정보나 이벤트를 알림으로 전달하기 위해 사용됩니다. Swift를 사용하여 로컬 알림을 특정 시간이 지난 후에 발생하도록 설정하는 방법을 알아보겠습니다.

1. 프로젝트에 UserNotifications 프레임워크 추가

먼저, 프로젝트에 UserNotifications 프레임워크를 추가해야 합니다. Xcode에서 프로젝트를 열고, 프로젝트 네비게이터에서 타겟을 선택한 다음, “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. 로컬 알림 설정

로컬 알림을 설정하려면 UNUserNotificationCenter를 사용해야 합니다. 다음은 로컬 알림을 1분 후에 발생하도록 설정하는 예제 코드입니다:

import UserNotifications

func scheduleLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "알림 제목"
    content.body = "알림 내용"
    content.sound = UNNotificationSound.default
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
    
    let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error {
            print("로컬 알림 설정 실패: \(error.localizedDescription)")
        } else {
            print("로컬 알림 설정 성공")
        }
    }
}

위 코드에서, UNMutableNotificationContent 객체를 생성하고 알림의 제목, 내용 및 사운드를 설정합니다. UNTimeIntervalNotificationTrigger를 사용하여 알림이 1분 후에 발생하도록 설정합니다. 마지막으로, UNNotificationRequest를 생성하고 UNUserNotificationCenter를 사용하여 알림을 추가합니다.

4. 알림 취소

로컬 알림을 취소하려면, 해당 알림의 identifier를 사용하여 UNUserNotificationCenter에서 알림 요청을 제거하면 됩니다. 다음은 알림을 취소하는 예제 코드입니다:

import UserNotifications

func cancelLocalNotification() {
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["localNotification"])
}

위 코드에서, removePendingNotificationRequests(withIdentifiers:) 메서드를 사용하여 “localNotification”이라는 identifier를 가진 알림 요청을 제거합니다.

참고 자료