[swift] Swift에서 로컬 알림을 앱이 백그라운드 상태일 때 발생하도록 설정하는 방법

로컬 알림은 사용자에게 중요한 정보를 알려주기 위해 앱에서 발생시킬 수 있는 알림입니다. Swift를 사용하여 로컬 알림을 앱이 백그라운드 상태일 때 발생하도록 설정하는 방법에 대해 알아보겠습니다.

Step 1: 알림 권한 요청

앱에서 로컬 알림을 사용하기 위해 먼저 알림 권한을 요청해야 합니다. AppDelegate.swift 파일에 다음 코드를 추가합니다.

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            if granted {
                UNUserNotificationCenter.current().delegate = self
            }
        }
        
        return true
    }
    
    // 앱이 활성화된 상태에서 알림이 도착했을 때 처리하는 메소드
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }
    
    // 알림을 터치하여 실행했을 때 처리하는 메소드
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림을 터치하여 실행한 경우 추가 작업이 필요한 경우 이곳에 구현
        completionHandler()
    }
}

Step 2: 로컬 알림 설정

로컬 알림을 설정하려면 앱의 적절한 위치에서 아래와 같이 코드를 작성해야 합니다.

import UIKit
import UserNotifications

func scheduleLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "로컬 알림"
    content.body = "앱이 백그라운드에 있을 때 알림이 발생합니다."
    content.sound = UNNotificationSound.default
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
    
    let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

위의 코드는 60초 후에 한 번만 알림을 발생시키는 예시입니다. 원하는 시간 간격 및 반복 설정을 통해 로컬 알림을 조정할 수 있습니다.

Step 3: 알림 예약하기

로컬 알림을 예약하려면 적절한 시기에 scheduleLocalNotification() 함수를 호출하면 됩니다. 예를 들어, 앱이 백그라운드로 전환될 때나 특정 이벤트가 발생했을 때 알림을 예약할 수 있습니다.

override func viewDidLoad() {
    super.viewDidLoad()
    
    NotificationCenter.default.addObserver(self, selector: #selector(scheduleNotification), name: UIApplication.didEnterBackgroundNotification, object: nil)
}

@objc func scheduleNotification() {
    scheduleLocalNotification()
}

위의 코드는 앱이 백그라운드로 전환될 때 scheduleNotification() 함수를 호출하여 로컬 알림을 예약하는 예시입니다.

이제 Swift에서 로컬 알림을 앱이 백그라운드 상태일 때 발생하도록 설정하는 방법에 대해 알아보았습니다. 이 방법을 사용하여 앱에서 중요한 정보를 사용자에게 전달할 수 있습니다.

참고 문서: