[swift] Swift에서 로컬 알림을 앱이 실행 중일 때만 발생하도록 설정하는 방법

iOS 개발에서 로컬 알림은 사용자에게 시간 또는 위치 기반의 알림을 통해 정보를 전달하는 방법으로 자주 사용됩니다. 앱이 실행 중일 때 로컬 알림을 발생시키면 사용자에게 즉각적인 피드백을 제공할 수 있습니다.

Swift에서는 UserNotifications 프레임워크를 사용하여 로컬 알림을 구현할 수 있습니다. 아래는 Swift 코드를 사용하여 로컬 알림을 앱이 실행 중일 때만 발생하도록 설정하는 방법입니다.

Step 1: UserNotifications 프레임워크 가져오기

먼저, UserNotifications 프레임워크를 가져와야 합니다. 아래 코드를 AppDelegate.swift 파일에 추가하세요.

import UserNotifications

Step 2: 알림 권한 요청하기

로컬 알림을 발생시키기 전에 사용자에게 알림 권한을 요청해야 합니다. 이를 위해 앱이 시작될 때 registerForRemoteNotifications() 함수를 호출해야 합니다. 아래 코드를 AppDelegate.swift 파일의 didFinishLaunchingWithOptions 메서드에 추가하세요.

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
}

Step 3: 알림 등록하기

알림을 등록하려면 UNUserNotificationCenter.current().add 메서드를 사용해야 합니다. 앱이 실행 중일 때 알림을 발생시키기 위해 UNNotificationTriggerUNTimeIntervalNotificationTrigger를 사용합니다. 아래 코드를 알림을 발생시키고자 하는 메서드에 추가하세요.

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

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, 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("알림 등록 성공")
    }
}

위 코드에서 timeInterval 매개변수는 알림이 발생되기까지의 시간을 초 단위로 나타냅니다. repeats 매개변수를 true로 설정하면 반복 알림을 설정할 수 있습니다.

이제 위의 코드를 실행하면 앱이 실행 중일 때 5초 후에 알림이 발생합니다. 알림이 발생하는지 확인하려면 iOS 시뮬레이터에서 앱을 실행하고 백그라운드에서 실행되는 동안 기다린 후 알림 센터를 확인하세요.

결론

Swift에서 로컬 알림을 앱이 실행 중일 때만 발생하도록 설정하는 방법을 배웠습니다. 이를 통해 사용자에게 즉각적인 피드백을 제공하고 앱의 사용자 경험을 향상시킬 수 있습니다.

더 자세한 내용은 Apple 개발자 문서를 참고하세요.