[swift] 스택 뷰에서의 알람 설정과 알림 기능 구현 방법

앱 개발에서 알림 기능은 사용자에게 중요한 정보를 전달하고, 알람 설정은 사용자가 특정 시간에 알림을 받을 수 있도록 하는 기능입니다. 이번 포스트에서는 스택 뷰에서의 알람 설정과 알림 기능을 구현하는 방법에 대해 알아보겠습니다.

1. UNUserNotificationCenter 설정

알람 기능을 사용하기 위해서는 UNUserNotificationCenter 클래스를 설정해야 합니다. 이 클래스는 iOS 알림을 관리하고 표시하는 데 사용됩니다. AppDelegate.swift 파일에 다음 코드를 추가합니다.

import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("알림 권한 허용됨")
            } else {
                print("알림 권한 거부됨")
            }
        }
        return true
    }
}

이 코드는 앱이 실행될 때 알림 권한을 요청하는 코드입니다. 사용자에게 알림 권한을 허용 또는 거부할 수 있도록 합니다.

2. 알람 설정 화면 구현

알람 설정 화면은 사용자가 알림을 설정하는 화면입니다. 시간을 선택하고 알림을 설정할 수 있는 인터페이스를 제공해야 합니다.

알람 설정을 위한 ViewController.swift 파일을 생성하고, 다음과 같이 코드를 추가합니다.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var timePicker: UIDatePicker!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 초기에 현재 시간으로 설정
        timePicker.date = Date()
    }

    @IBAction func setAlarmButtonTapped(_ sender: Any) {
        let alarmTime = timePicker.date

        // 알림 설정 메서드 호출
        setNotification(at: alarmTime)
    }

    func setNotification(at date: Date) {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.hour, .minute], from: date)

        let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

        let content = UNMutableNotificationContent()
        content.title = "알림"
        content.body = "알림 내용"

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

        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("알림 설정 실패: \(error.localizedDescription)")
            } else {
                print("알림 설정 성공")
            }
        }
    }
}

이 코드에서는 사용자가 UIDatePicker를 사용하여 알람 시간을 선택하고, “알람 설정” 버튼을 누르면 알림을 설정하는 로직을 구현합니다.

3. 알람 표시 처리

알람이 설정된 시간에 도달하면, 앱은 백그라운드 상태에서도 알림을 표시할 수 있어야 합니다. AppDelegate.swift 파일의 didFinishLaunchingWithOptions 메서드에 다음 코드를 추가하여 앱이 백그라운드에 있을 때도 알림을 표시하도록 합니다.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    //...

    UNUserNotificationCenter.current().delegate = self

    return true
}

그리고 AppDelegate.swift 파일에 UNUserNotificationCenterDelegate 프로토콜을 구현하기 위해 다음 코드를 추가합니다.

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }
}

이 코드는 알림이 표시될 때 어떤 옵션을 선택할 지를 결정합니다.

마치며

이제 알람 설정과 알림 기능을 구현하는 방법을 알게 되었습니다. 앱의 사용자 경험을 향상시키고 사용자에게 중요한 정보를 제공하기 위해 알림 기능을 적절히 활용해 보세요.