[swift] 백그라운드 상태에서 알림 처리 방법

앱은 백그라운드에서 실행 중인 동안도 알림을 받을 수 있도록 구현할 수 있습니다. 백그라운드 상태에서 알림을 처리하는 방법에 대해 알아보겠습니다.

1. 알림 권한 요청

앱이 백그라운드에서 알림을 수신하려면 먼저 사용자의 권한을 받아야 합니다. AppDelegate 클래스의 didFinishLaunchingWithOptions 메서드에서 다음과 같이 권한을 요청할 수 있습니다.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 알림 권한 요청
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if let error = error {
            print("알림 권한 요청 실패: \(error.localizedDescription)")
        } else if granted {
            print("알림 권한 요청 승인됨")
        } else {
            print("알림 권한 요청 거부됨")
        }
    }
    
    return true
}

이 코드는 사용자에게 알림을 허용할지 묻는 확인 대화상자를 표시하고, 결과에 따라 콜백을 처리합니다. 사용자가 알림 권한을 허용하면 “알림 권한 요청 승인됨” 메시지가 출력됩니다.

2. 알림 등록

알림을 받을 시기와 내용을 설정합니다. 예를 들어, 특정 시간에 매일 알림을 받으려면 다음과 같이 알림을 등록할 수 있습니다.

func scheduleNotification() {
    let content = UNMutableNotificationContent()
    content.title = "일일 알림"
    content.body = "매일 같은 시간에 알림을 받습니다."
    content.sound = .default
    
    var dateComponents = DateComponents()
    dateComponents.hour = 10
    dateComponents.minute = 0
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    
    let request = UNNotificationRequest(identifier: "dailyNotification", content: content, trigger: trigger)
    
    let center = UNUserNotificationCenter.current()
    center.add(request) { (error) in
        if let error = error {
            print("알림 등록 실패: \(error.localizedDescription)")
        } else {
            print("알림 등록 성공")
        }
    }
}

이 코드는 UNMutableNotificationContent 객체를 생성하여 알림의 제목, 내용 및 사운드를 설정합니다. 그런 다음 UNCalendarNotificationTrigger를 사용하여 매일 같은 시간에 알림을 트리거하는 설정을 만듭니다. 마지막으로 UNNotificationRequest 객체를 생성하여 알림 요청을 만들고, UNUserNotificationCenter를 사용하여 알림을 등록합니다.

3. 알림 수신

백그라운드 상태에서 알림을 수신하려면 AppDelegate 클래스에 UNUserNotificationCenterDelegate 프로토콜을 채택하고, didReceive 메서드를 구현해야 합니다.

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림 수신 처리
        completionHandler()
    }
}

이 코드는 알림을 수신할 때 호출되는 didReceive 메서드를 구현합니다. 이 메서드에서는 알림과 상호 작용할 수 있으며, 알림을 처리한 후 completionHandler를 호출하여 작업이 완료되었음을 시스템에 알립니다.

결론

위의 단계를 따라하면 앱이 백그라운드 상태에서도 알림을 받을 수 있게 됩니다. 알림 권한 요청, 알림 등록 및 알림 수신 처리를 구현하여 사용자에게 필요한 정보를 정확히 전달할 수 있습니다.

참고 자료:

수고하셨습니다!