[swift] Swift에서 로컬 알림이 발생한 시간과 날짜를 로그로 출력하는 방법
import UIKit
import UserNotifications

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 알림 발생 시간과 날짜를 확인하기 위해 UNUserNotificationCenterDelegate를 설정합니다.
        UNUserNotificationCenter.current().delegate = self
        
        // 앱 시작 시 로컬 알림을 생성합니다.
        createLocalNotification()
    }
    
    func createLocalNotification() {
        let content = UNMutableNotificationContent()
        content.title = "로컬 알림 테스트"
        content.body = "알림이 발생한 시간과 날짜를 확인해보세요."
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        
        let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }
    
}

// UNUserNotificationCenterDelegate 프로토콜을 구현하여 알림의 발생 시간과 날짜를 로그로 출력합니다.
extension ViewController: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        // 알림이 발생한 시간과 날짜를 로그로 출력합니다.
        let date = notification.date
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateString = dateFormatter.string(from: date)
        
        print("로컬 알림이 발생한 시간과 날짜:", dateString)
        
        completionHandler(.alert)
    }
    
}

위의 예제 코드는 Swift로 로컬 알림을 생성하고, 알림이 발생한 시간과 날짜를 출력하는 기능을 포함하고 있습니다. createLocalNotification() 함수에서는 5초 후에 알림이 발생하도록 설정하고, UNUserNotificationCenterDelegate를 구현한 확장(extension)을 사용하여 알림의 발생 시간과 날짜를 출력합니다.

앱을 실행하고 5초가 지나면 알림이 발생하며, 콘솔에 로그로 알림이 발생한 시간과 날짜가 출력됩니다.

참고 자료: