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

로컬 알림은 사용자가 앱으로부터 오프라인일 때도 중요한 정보를 전달할 수 있는 기능입니다. 하지만 앱이 백그라운드 상태일 때만 로컬 알림을 발생시키기를 원할 수도 있습니다. Swift에서 이를 설정하는 방법을 알아보겠습니다.

1. 앱의 Capabilities 설정

먼저, 앱의 Capabilities 설정에서 “Background Modes”를 활성화해야 합니다. 다음은 설정하는 방법입니다.

  1. Xcode에서 프로젝트를 엽니다.
  2. Target을 선택하고 “Signing & Capabilities” 탭을 엽니다.
  3. “Background Modes” 섹션을 찾고 체크박스를 선택합니다.
  4. “Remote notifications”를 선택합니다.

2. AppDelegate.swift 파일 수정

AppDelegate.swift 파일에서 didFinishLaunchingWithOptions 메소드를 수정하여 백그라운드 상태에서 로컬 알림을 처리할 수 있도록 설정해야 합니다. 다음은 코드의 일부입니다.

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  
    UNUserNotificationCenter.current().delegate = self
    
    // 로컬 알림 허용 요청
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        if granted {
            // 알림 허용 시 로직을 추가할 수 있습니다.
        }
    }
    
    return true
  }
  
  func applicationDidEnterBackground(_ application: UIApplication) {
    // 앱이 백그라운드 상태로 전환되면 로컬 알림 예약
    scheduleLocalNotification()
  }

  func scheduleLocalNotification() {
    // 로컬 알림 예약 코드를 작성합니다.
  }
}

위의 코드에서 scheduleLocalNotification 메소드는 앱이 백그라운드 상태로 전환될 때 호출되는 메소드로, 여기에서 로컬 알림을 예약하는 코드를 작성해야 합니다.

3. 로컬 알림 예약하기

로컬 알림을 예약하는 기능은 UNUserNotificationCenter를 사용하여 구현할 수 있습니다. 예를 들어, 아래의 코드는 5초 후에 알림을 예약하는 예입니다.

func scheduleLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "로컬 알림"
    content.body = "앱 백그라운드 상태일 때 발생하는 알림입니다."
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request)
}

위의 코드를 scheduleLocalNotification 메소드에 추가하면 앱이 백그라운드 상태로 전환될 때 5초 후에 로컬 알림이 발생합니다.

결론

Swift에서 로컬 알림을 앱이 백그라운드 상태일 때만 발생할 수 있도록 설정하기 위해 앱의 Capabilities 설정과 AppDelegate 파일을 수정해야 합니다. 이를 통해 사용자가 오프라인일 때도 중요한 정보를 전달할 수 있는 로컬 알림 기능을 구현할 수 있습니다.


참고 자료: