[swift] Swift에서 로컬 알림을 앱이 활성 상태일 때 발생하도록 설정하는 방법

로컬 알림은 iOS 앱에서 사용자에게 중요한 정보나 이벤트를 알리는 데 사용됩니다. Swift를 사용하여 앱이 활성 상태일 때 로컬 알림을 발생하도록 설정하는 방법을 알아보겠습니다.

1. UserNotifications 프레임워크 추가

첫 번째로, Xcode 프로젝트에 UserNotifications 프레임워크를 추가해야 합니다. 프로젝트 네비게이터에서 타겟을 선택하고 “Build Phases” 탭으로 이동한 다음, “Link Binary With Libraries” 섹션에 UserNotifications.framework을 추가합니다.

2. 알림 권한 요청

앱이 로컬 알림을 보낼 수 있도록 권한을 요청해야 합니다. 일반적으로 앱이 처음 실행될 때 사용자에게 권한을 요청하는 것이 좋습니다. 다음은 권한을 요청하는 코드 예시입니다.

import UserNotifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
    if granted {
        print("알림 권한이 허용되었습니다.")
    } else {
        print("알림 권한이 거부되었습니다.")
    }
}

3. 로컬 알림 생성 및 예약

로컬 알림을 생성하고 예약하기 위해 UNMutableNotificationContent, UNNotificationTrigger, UNNotificationRequest 등의 클래스를 사용해야 합니다. 아래는 알림을 생성하고 예약하는 코드 예시입니다.

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

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

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

UNUserNotificationCenter.current().add(request) { (error) in
    if error != nil {
        print("로컬 알림 예약 중 오류 발생: \(error!.localizedDescription)")
    }
}

위의 예시에서 timeInterval 매개변수는 알림을 발생시킬 시간 간격을 초 단위로 설정합니다. 이 예시에서는 5초 후에 알림이 발생합니다.

4. 알림 수신 및 처리

앱이 활성 상태일 때 로컬 알림을 수신하고 처리해야 합니다. 이를 위해 UNUserNotificationCenterDelegate 프로토콜을 채택하고, 알림을 수신하는 메서드를 구현해야 합니다.

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, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound]) // 알림을 화면에 표시하고 사운드 재생
    }
    
    // 다른 UNUserNotificationCenterDelegate 메서드도 필요한 경우 추가 가능
    
}

위의 예시에서 willPresent 메서드는 앱이 활성 상태일 때 알림을 화면에 표시하고 사운드를 재생합니다.

이제 Swift를 사용하여 앱이 활성 상태일 때 로컬 알림을 발생하도록 설정할 수 있습니다. 참고로, 알림에서 사용할 이미지, 사운드 등의 추가적인 설정은 UNNotificationAttachment, UNNotificationSound 등의 클래스를 사용하여 구현할 수 있습니다.

참고 자료