[swift] Swift에서 로컬 알림을 특정 날짜와 시간에 예약하는 방법

iOS 앱에서 로컬 알림을 사용하여 특정 날짜와 시간에 알림을 예약할 수 있습니다. 이를 위해 Swift에서 제공하는 UserNotifications 프레임워크를 사용하면 간편하게 구현할 수 있습니다.

UserNotifications 프레임워크 추가

Xcode 프로젝트에서 UserNotifications 프레임워크를 추가해줍니다. 이를 위해 다음 단계를 따릅니다.

  1. 프로젝트 네비게이터에서 앱의 타겟을 선택합니다.
  2. “General” 탭을 선택합니다.
  3. “Frameworks, Libraries, and Embedded Content” 섹션 아래에서 “+” 버튼을 클릭합니다.
  4. “UserNotifications.framework”을 선택하고 “Add” 버튼을 클릭합니다.

알림 권한 요청

로컬 알림을 사용하기 전에 앱 사용자로부터 알림 권한을 요청해야 합니다. AppDelegate.swift 파일에서 다음 코드를 추가해주세요.

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

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

        return true
    }
}

이 코드는 앱이 처음 실행될 때 알림 권한 요청 창을 표시하고 사용자가 권한을 허용하거나 거부할 때 콜백을 받아 처리합니다.

로컬 알림 예약

로컬 알림을 예약하기 위해 다음 코드를 사용할 수 있습니다. 특정 날짜와 시간을 지정하고 알림 내용, 사운드 및 기타 옵션을 설정할 수 있습니다.

import UserNotifications

// 예약할 날짜와 시간 설정
let dateComponents = DateComponents(year: 2022, month: 12, day: 31, hour: 23, minute: 59)

// 알림 컨텐츠 설정
let content = UNMutableNotificationContent()
content.title = "새해 복 많이 받으세요!"
content.body = "2022년이 시작됩니다. 새해 복 많이 받으세요!"
content.sound = UNNotificationSound.default

// 알림 요청 설정
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "NewYearNotification", content: content, trigger: trigger)

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

위 코드에서는 2022년 12월 31일 23시 59분에 알림을 예약하는 예제입니다. dateComponents 변수에 원하는 날짜와 시간을 설정한 후, content 변수에 알림 내용을 설정합니다. 알림을 예약하기 위해 triggerrequest를 설정한 후 UNUserNotificationCenter.current().add(request)를 호출하여 알림을 예약합니다.

알림 예약에 성공하면 “알림 예약 성공”이 출력되고, 실패하면 “알림 예약 실패”와 함께 오류 메시지가 출력됩니다.

참고 자료