[swift] Swift PromiseKit를 활용한 알림 및 푸시 알림 처리

알림 및 푸시 알림은 모바일 앱에서 중요한 기능입니다. Swift PromiseKit을 사용하여 이러한 알림을 처리하는 방법을 소개하겠습니다.

PromiseKit 소개

PromiseKit은 Swift에서 비동기 작업을 처리하기 위한 라이브러리입니다. 비동기 작업을 처리하기 위해 사용되는 Promise 객체를 제공하며, 이를 활용하여 코드를 간결하게 작성할 수 있습니다.

알림 처리

  1. 사용자에게 알림 권한 요청

첫 번째 단계는 사용자에게 알림 권한을 요청하는 것입니다. 이러한 권한을 얻기 위해 UNUserNotificationCenter를 사용할 수 있습니다.

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
    if granted {
        // 권한이 부여됨
        // 알림을 등록하거나 푸시 알림을 제어할 수 있음
    } else {
        // 권한이 거부됨
        // 알림을 등록하거나 푸시 알림을 제어할 수 없음
    }
}
  1. 알림 등록

UNUserNotificationCenteradd 메서드를 사용하여 알림을 등록할 수 있습니다. 알림에는 제목, 내용, 알림 소리 등의 속성을 설정할 수 있습니다.

let content = UNMutableNotificationContent()
content.title = "새로운 알림"
content.body = "알림 내용..."
content.sound = UNNotificationSound.default

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

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

UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("알림 등록 실패: \(error)")
    } else {
        print("알림 등록 성공")
    }
}

푸시 알림 처리

푸시 알림은 앱 외부에서 알림을 전송하는 기능입니다. 알림을 수신하기 위해 UNUserNotificationCenterDelegate 프로토콜을 구현해야 합니다.

  1. AppDelegateUNUserNotificationCenterDelegate 적용
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    // ...
}
  1. Delegate 메서드 구현
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) {
    // 알림을 눌렀을 때 호출됨
    // 알림에 대한 처리를 수행할 수 있음
    completionHandler()
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // 앱이 foreground에서 실행 중일 때 호출됨
    // 배경에서 동작하도록 설정하거나, 알림을 무시할 수 있음
    completionHandler([.alert, .sound])
}

결론

Swift PromiseKit을 사용하여 알림 및 푸시 알림을 처리할 수 있습니다. PromiseKit을 활용하면 비동기 작업을 간결하게 처리할 수 있으며, 사용자에게 직관적인 알림을 제공할 수 있습니다. 알림 처리는 모바일 앱 개발에 있어서 중요한 요소 중 하나이므로, PromiseKit의 활용은 매우 유용합니다.

참조: PromiseKit 공식 문서