[swift] Swift에서 로컬 알림을 특정 조건을 만족할 때마다 발생하도록 설정하는 방법

로컬 알림은 사용자에게 앱 내부에서 발생하는 메시지로, 특정 조건이 충족되었을 때 사용자에게 알림을 보여줄 수 있습니다. Swift에서는 UserNotifications 프레임워크를 사용하여 로컬 알림을 설정할 수 있습니다.

아래는 특정 조건을 만족할 때마다 로컬 알림을 발생시키는 방법입니다.

1. UserNotifications 프레임워크를 import 하기

먼저, UserNotifications 프레임워크를 import 해야 합니다. 아래 코드를 앱의 ViewController.swift 파일에 추가하세요.

import UserNotifications

2. 로컬 알림 요청 생성하기

로컬 알림을 발생시키기 위해서는 알림 요청을 생성해야 합니다. 알림 요청은 알림의 콘텐츠와 발생 조건을 정의합니다. 아래 코드는 특정 조건을 만족할 때마다 로컬 알림을 발생시키는 예제입니다.

func scheduleLocalNotification() {
    // 로컬 알림 콘텐츠 생성
    let content = UNMutableNotificationContent()
    content.title = "로컬 알림"
    content.subtitle = "조건이 충족되었습니다."
    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: "notification", content: content, trigger: trigger)
    
    // 알림 요청 등록
    UNUserNotificationCenter.current().add(request) { (error: Error?) in
        if let error = error {
            print("로컬 알림 요청 등록 실패: \(error)")
        } else {
            print("로컬 알림 요청 등록 성공")
        }
    }
}

위 코드에서 scheduleLocalNotification() 함수는 조건을 설정하고 알림 요청을 생성하는 부분입니다. 알림 콘텐츠를 생성한 후, 알림이 발생하는 시간을 설정하고 특정 조건(예: 시간이 8시 0분)을 확인하는 트리거를 생성합니다. 마지막으로 알림 요청을 등록합니다.

3. 알림 등록 요청하기

로컬 알림을 사용하려면 앱이 알림을 등록하도록 허용해야 합니다. AppDelegate.swift 파일의 didFinishLaunchingWithOptions 메서드에 아래 코드를 추가하여 알림 등록을 요청합니다.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 알림 등록 요청
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        if let error = error {
            print("알림 등록 실패: \(error)")
        } else {
            print("알림 등록 성공")
        }
    }
    
    return true
}

위 코드에서 requestAuthorization 메서드로 알림 승인을 요청하고, .alert, .sound, .badge 등의 옵션을 설정하여 알림 스타일을 지정합니다.

이제 앱을 실행하면 특정 조건이 충족되었을 때마다 로컬 알림이 발생할 것입니다. 알림을 정확히 처리하기 위해 앱의 설정에서 알림 권한을 설정해야 합니다.

더 자세한 내용은 UNUserNotificationCenter 문서를 참고하십시오.