[swift] PushKit을 사용하여 Swift에서 푸시 알림 구현하기

PushKit은 iOS 앱에서 실시간 VoIP 알림과 같은 백그라운드 알림을 처리하기 위한 Apple 프레임워크입니다. 이를 사용하면 앱이 포그라운드가 아닐 때도 중요한 알림을 실시간으로 받을 수 있습니다.

이 글에서는 Swift를 사용하여 PushKit을 구현하는 방법을 알아보겠습니다.

PushKit 설정

  1. 프로젝트 타겟 설정에서 “Capabilities” 탭으로 이동합니다.
  2. Push Notifications을 켜고, Background Modes를 활성화하여 “VoIP” 옵션을 선택합니다.

PushKit 등록

PushKit을 사용하기 위해 앱을 등록해야 합니다. AppDelegate.swift 파일을 열고 다음 코드를 추가합니다.

import PushKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let pushRegistry = PKPushRegistry(queue: DispatchQueue.main)
        pushRegistry.delegate = self
        pushRegistry.desiredPushTypes = [PKPushType.voIP]
        return true
    }

    // PushKit delegate methods

    func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
        // 푸시 알림 등록 성공시 호출
        let token = pushCredentials.token
        // 서버로 토큰 전송 등 추가 작업
    }

    func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
        // 백그라운드 알림 수신시 호출
        let payloadDict = payload.dictionaryPayload
        // 알림 처리 등 추가 작업
    }
}

위 코드에서 PushKit을 등록하기 위해 PKPushRegistry를 사용하고, pushRegistry(_:didUpdate:for:)pushRegistry(_:didReceiveIncomingPushWith:for:) 메서드를 구현합니다.

pushRegistry(_:didUpdate:for:) 메서드는 푸시 알림 등록 성공 시 호출되며, 서버로 토큰을 전송하거나 추가 작업을 수행할 수 있는 곳입니다.

pushRegistry(_:didReceiveIncomingPushWith:for:) 메서드는 백그라운드 알림을 수신하면 호출되며, 받은 알림을 처리하거나 필요한 작업을 수행할 수 있습니다.

알림 수신 처리

PushKit을 통해 받은 알림을 처리하려면 다음과 같이 처리할 수 있습니다.

import UserNotifications

func handleIncomingPushNotification(payload: [AnyHashable: Any]) {
    let aps = payload["aps"] as? [String: Any]
    let alert = aps?["alert"] as? [String: Any]
    let title = alert?["title"] as? String
    let body = abody["body"] as? String

    // 알림 처리 등 필요한 작업 수행
}

위 코드에서 handleIncomingPushNotification 함수는 PushKit으로 받은 알림을 처리하기 위한 로직을 포함하고 있습니다.

위 예제에서는 payload에서 알림의 제목과 내용을 추출하여 필요한 작업을 수행하도록 하였습니다.

결론

이제 Swift에서 PushKit을 사용하여 푸시 알림을 구현하는 방법을 알게되었습니다. PushKit을 사용하면 백그라운드에서도 알림을 실시간으로 받을 수 있어서 실시간 메시징 앱이나 기타 실시간 동작이 필요한 앱에 적합합니다.

더 자세한 내용은 Apple의 PushKit 문서를 참고하세요.