[swift] Swift에서 로컬 알림의 메시지 실행 시 앱을 실행하는 방법

Swift에서 로컬 알림을 사용하여 푸시 알림을 구현할 때, 사용자가 알림을 탭하면 해당 앱을 실행하도록 설정하는 방법을 알아보겠습니다.

1. 알림 권한 설정

먼저, 앱에서 로컬 알림을 사용하려면 사용자에게 알림 권한을 요청해야 합니다.

import UserNotifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in
     // 알림 권한 요청 완료 후에 실행할 코드
}

위의 코드에서 requestAuthorization 메서드를 호출하여 사용자에게 알림 권한을 요청합니다. .alert, .badge, .sound 등의 옵션을 사용하여 알림 스타일을 설정할 수 있습니다.

2. 로컬 알림 생성하기

알림을 생성하여 특정 시간에 사용자에게 보여줄 수 있습니다. 예를 들어, 5초 후에 로컬 알림을 표시하려면 다음과 같이 코드를 작성합니다.

let content = UNMutableNotificationContent()
content.title = "새로운 알림"
content.body = "안녕하세요! 새로운 알림입니다."
content.sound = .default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

let request = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("알림 추가 실패: \(error.localizedDescription)")
    } else {
        print("알림이 성공적으로 추가되었습니다.")
    }
}

위의 코드에서 UNMutableNotificationContent 클래스를 사용하여 알림 내용을 설정합니다. UNTimeIntervalNotificationTrigger 클래스를 사용하여 특정 시간 간격에 알림을 트리거하도록 설정합니다. 그리고 UNNotificationRequest 객체를 생성하여 알림을 추가합니다.

3. 알림 터치 시 앱 실행하기

이제 알림을 탭하면 앱이 실행되도록 설정해야 합니다. AppDelegate 파일에서 다음과 같이 코드를 추가합니다.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    // ...

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        return true
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
            // 알림을 터치하여 앱을 실행하는 로직을 작성합니다.
            // 예: 특정 ViewController를 present하는 등의 작업 수행
            
            completionHandler()
        }
    }
}

위의 코드에서 UNUserNotificationCenterDelegate 프로토콜을 채택하여 userNotificationCenter(_:didReceive:withCompletionHandler:) 메서드에서 알림을 터치했을 때 실행될 로직을 작성합니다. 여기에서는 원하는 작업을 수행한 후 completionHandler를 호출합니다.

이러한 방식으로 Swift에서 로컬 알림의 메시지를 터치하여 앱을 실행할 수 있습니다.

참고 자료