[swift] Swift에서 로컬 알림을 발생시키면서 특정 동작을 수행하는 방법

로컬 알림은 사용자의 디바이스에게 알림을 보내는 기능입니다. Swift를 사용하여 로컬 알림을 발생시키고 동작을 수행하는 방법에 대해 알아보겠습니다.

1. UserNotifications 프레임워크 가져오기

로컬 알림을 사용하기 위해, UserNotifications 프레임워크를 가져와야 합니다. 이 프레임워크를 추가하는 방법은 다음과 같습니다:

import UserNotifications

2. UNUserNotificationCenter 설정

로컬 알림을 발생시키기 전에, UNUserNotificationCenter를 설정해야 합니다. 알림 권한을 요청하고, 알림 동작을 처리할 delegate를 설정합니다. 다음 코드를 사용하여 설정할 수 있습니다:

let center = UNUserNotificationCenter.current()
center.delegate = self

center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    if let error = error {
        // 알림 권한 요청 중 오류가 발생한 경우 처리
        print("알림 권한 요청 오류: \(error.localizedDescription)")
    } else {
        // 알림 권한 요청이 성공한 경우 처리
        // 알림 동작을 설정, 예를 들어 사용자가 알림을 탭했을 때 수행할 동작 등
    }
}

3. 로컬 알림 생성 및 예약

로컬 알림을 생성하고 예약하는 방법은 다음과 같습니다:

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

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)

let request = UNNotificationRequest(identifier: "uniqueIdentifier", content: content, trigger: trigger)

center.add(request) { error in
    if let error = error {
        // 로컬 알림 예약 중 오류가 발생한 경우 처리
        print("알림 예약 오류: \(error.localizedDescription)")
    } else {
        // 로컬 알림이 성공적으로 예약된 경우 처리
    }
}

위 코드에서, UNMutableNotificationContent를 사용하여 알림의 제목, 내용, 사운드 등을 설정할 수 있습니다. UNTimeIntervalNotificationTrigger를 사용하여 알림이 발생되는 시간을 설정하고, UNNotificationRequest를 사용하여 알림을 식별하는 고유한 식별자, 내용, 트리거를 설정합니다.

4. UNUserNotificationCenterDelegate 구현

로컬 알림 동작을 처리하기 위해, UNUserNotificationCenterDelegate를 구현해야 합니다. 다음과 같이 동작을 수행할 메서드를 추가합니다:

extension ViewController: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림 동작을 처리하는 코드를 작성합니다.
        // 예를 들어, 특정 화면으로 이동 또는 특정 동작을 수행하는 등
    }
}

위 코드에서 didReceive 메서드는 사용자가 알림에 반응하였을 때 호출되는 메서드입니다. 이 메서드에서는 사용자의 동작에 따라 특정 동작을 수행할 수 있습니다.

참고 자료