[swift] Swift Device의 알림 및 알람 기능

Swift를 사용하여 iOS 애플리케이션을 개발할 때, 알림과 알람 기능을 구현할 수 있습니다. 이 문서에서는 Swift에서 기기 알림 및 알람을 처리하는 방법에 대해 다루겠습니다.

1. 알림(Notification) 기능

알림은 사용자에게 중요한 정보를 전달하거나 애플리케이션에 대한 알림을 제공하기 위해 사용됩니다. Swift에서 알림을 사용하기 위해서는 다음과 같은 단계를 진행합니다.

1.1. 알림 권한 요청

알림을 사용하기 위해서는 사용자의 권한이 필요합니다. 사용자에게 알림 권한을 요청하기 위해 UNUserNotificationCenter를 사용합니다. 다음은 알림 권한을 요청하는 코드의 예시입니다.

import UserNotifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
    if granted {
        print("알림 권한이 허용되었습니다.")
    } else {
        print("알림 권한이 거부되었습니다.")
    }
}

1.2. 알림 생성 및 예약

알림을 생성하고 예약하기 위해서는 UNMutableNotificationContentUNNotificationRequest를 사용합니다. UNMutableNotificationContent를 사용하여 알림의 내용을 설정하고, UNNotificationRequest를 사용하여 알림을 생성합니다. 다음은 알림을 예약하는 코드의 예시입니다.

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

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "NotificationIdentifier", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
    if let error = error {
        print("알림 예약에 실패했습니다. 에러: \(error)")
    } else {
        print("알림이 예약되었습니다.")
    }
}

1.3. 알림 수신 및 처리

알림을 수신하고 처리하기 위해서는 앱 델리게이트(App Delegate)에서 UNUserNotificationCenterDelegate 프로토콜을 채택하고, 알림 수신에 대한 처리를 구현해야 합니다. 다음은 알림을 수신하여 처리하는 코드의 예시입니다.

import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        return true
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 알림을 수신했을 때의 처리 로직
        // completionHandler를 사용하여 알림의 표시 옵션을 설정
        completionHandler([.alert, .sound, .badge])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림을 탭했을 때의 처리 로직
        completionHandler()
    }
}

2. 알람(Alarm) 기능

알람은 특정 시간에 사용자를 깨워주거나 알림을 주는 기능입니다. Swift에서 알람을 구현하기 위해서는 UNCalendarNotificationTrigger를 사용하여 알람을 예약합니다. 다음은 알람을 예약하는 코드의 예시입니다.

let content = UNMutableNotificationContent()
content.title = "알람 제목"
content.body = "알람 내용입니다."
content.sound = UNNotificationSound.default

var dateComponents = DateComponents()
dateComponents.hour = 8
dateComponents.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "AlarmIdentifier", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
    if let error = error {
        print("알람 예약에 실패했습니다. 에러: \(error)")
    } else {
        print("알람이 예약되었습니다.")
    }
}

알람은 알림과 유사한 방식으로 처리되며, 알림 처리 메서드와 같은 방법으로 알람을 수신하고 처리할 수 있습니다.

참고 자료