[swift] 스위프트에서의 UserNotifications을 이용한 알림 관리

스위프트 애플리케이션에서 알림을 관리하기 위해 UserNotifications 프레임워크를 사용할 수 있습니다. 이를 통해 사용자에게 알림을 보내고 관리할 수 있습니다.

알림 요청 생성

import UserNotifications

let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "새로운 메시지"
content.body = "알림 테스트입니다."
content.sound = UNNotificationSound.default

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

let request = UNNotificationRequest(identifier: "notification-1", content: content, trigger: trigger)

center.add(request) { (error) in
    if let error = error {
        print("알림 추가 실패: \(error.localizedDescription)")
    }
}

위의 코드는 5초 후에 한 번만 “새로운 메시지”라는 제목과 “알림 테스트입니다.”라는 내용을 갖는 알림을 생성하는 예시입니다.

권한 요청

알림을 보내기 전에 사용자로부터 권한을 요청해야 합니다. 아래는 권한 요청 방법의 예시입니다.

center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
    if granted {
        print("권한 허용됨")
    } else {
        print("권한 거부됨")
    }
}

알림 헨들링

사용자가 알림을 탭했을 때 알림에 대한 행동을 정의할 수 있습니다.

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림에 대한 행동 처리
        completionHandler()
    }
}

UserNotifications 프레임워크를 사용하면 사용자에게 알림을 보내고 다양한 알림 관련 작업을 수행할 수 있습니다.

더 많은 정보를 원하시면 Apple Developer Documentation를 참고하세요.