[swift] Swift에서 푸시 알림을 보내는 방법

푸시 알림은 사용자의 기기로 중요한 알림이나 업데이트를 전송할 때 매우 유용한 기능입니다. Swift에서 푸시 알림을 보내는 방법에 대해 알아보겠습니다.

1. Apple Developer 계정 등록

첫 번째로, Apple Developer 계정을 등록해야 합니다. 이 계정을 통해 푸시 알림 기능을 사용할 수 있습니다. Apple Developer 사이트에 가입하고 등록 프로세스를 완료하세요.

2. 프로젝트 설정

푸시 알림을 사용하려는 프로젝트를 엽니다. 다음으로, 타겟 설정을 클릭하고 “Signing & Capabilities” 탭을 선택합니다. “Capability” 섹션에서 “Push Notifications”을 활성화하십시오.

3. 인증서 및 프로비저닝 프로파일 생성

푸시 알림을 사용하려면 애플에서 제공하는 인증서와 프로비저닝 프로파일이 필요합니다. Apple Developer 사이트에서 인증서와 프로비저닝 프로파일을 생성하고 다운로드하세요.

4. Firebase 설정

Firebase는 푸시 알림을 관리하기 위해 사용될 수 있습니다. Firebase 콘솔로 이동하여 프로젝트를 생성하고, 푸시 알림 설정을 완료하세요. Firebase SDK를 추가하고 구성 파일을 다운로드하세요.

5. 프로젝트에 Firebase 추가

프로젝트에 Firebase SDK를 추가하여 푸시 알림을 보낼 수 있습니다. CocoaPods를 사용하는 경우, Podfile에 다음과 같은 내용을 추가하고 터미널에서 pod install을 실행하세요.

pod 'Firebase/Core'
pod 'Firebase/Messaging'

Firebase SDK를 수동으로 추가하려면 다운로드한 SDK를 프로젝트에 직접 추가하십시오.

6. AppDelegate 설정

AppDelegate.swift 파일을 열고 다음과 같은 코드를 추가하여 Firebase와 푸시 알림을 처리할 수 있도록 합니다.

// Firebase 라이브러리 임포트
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // Firebase 초기화
        FirebaseApp.configure()
        
        // 푸시 알림 등록
        self.registerForPushNotifications()
        
        return true
    }

    // 푸시 알림 등록 함수
    func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in
            guard granted else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("Device Token: \(tokenString)")
        
        // Firebase에 디바이스 토큰 등록
        let token = Messaging.messaging().fcmToken
        print("FCM Token: \(token ?? "")")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // 푸시 알림 수신 처리
    }

}

위의 코드에서 registerForPushNotifications() 함수는 푸시 알림 등록을 처리합니다. application(_:didRegisterForRemoteNotificationsWithDeviceToken:) 함수에서는 디바이스 토큰과 Firebase의 FCM Token을 출력합니다. application(_:didReceiveRemoteNotification:) 함수는 푸시 알림을 수신할 때 호출되며, 해당 함수에서 알림을 처리하십시오.

7. 푸시 알림 보내기

이제 앱에서 푸시 알림을 보낼 준비가 완료되었습니다. Firebase 콘솔로 돌아가서 “Cloud Messaging”을 선택하고 “푸시 알림 보내기” 기능을 사용하여 알림을 보낼 수 있습니다.

결론

Swift에서 푸시 알림을 보내는 방법에 대해 알아보았습니다. Apple Developer 계정을 등록하고 프로젝트를 설정한 다음, Firebase를 사용하여 푸시 알림을 관리할 수 있습니다. AppDelegate에서 Firebase를 초기화하고 푸시 알림 등록을 처리하는 코드를 추가한 후, Firebase 콘솔을 통해 푸시 알림을 보낼 수 있습니다.