[swift] Swift에서 푸시 알림을 사용하여 소셜 미디어 알림 제공하기

소셜 미디어 애플리케이션을 개발 중이고 사용자에게 푸시 알림을 제공하고자 한다면, Swift에서 이를 구현하는 방법을 알아보겠습니다. 푸시 알림은 사용자에게 새로운 메시지, 좋아요 등의 알림을 보내는데 사용됩니다.

1. Firebase 프로젝트 설정

Firebase를 사용하여 푸시 알림을 구현하기 위해 먼저 Firebase 프로젝트를 설정해야 합니다. Firebase 콘솔(https://console.firebase.google.com/)에 로그인하여 새 프로젝트를 생성하고 iOS 앱을 추가합니다. Firebase SDK를 추가하고, 푸시 알림을 위한 인증 키를 생성합니다.

2. 앱에 Firebase SDK 추가

프로젝트에 Firebase SDK를 추가해야 합니다. Podfile을 열고 다음과 같이 Firebase와 Firebase 푸시 알림 라이브러리를 추가합니다.

target 'YourAppName' do
   pod 'Firebase/Core'
   pod 'Firebase/Messaging'
end

터미널에서 pod install 명령을 실행하여 라이브러리를 설치합니다.

3. AppDelegate 설정

Firebase SDK를 초기화하고 푸시 알림과 관련된 작업을 처리하기 위해 AppDelegate 클래스를 업데이트해야 합니다.

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        
        // 푸시 알림 등록
        if #available(iOS 10.0, *) {
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
        application.registerForRemoteNotifications()
        
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("Device Token: \(tokenString)")
        
        // 토큰 서버로 전송 등의 추가 작업 수행
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // 푸시 알림 수신시 추가 작업 수행
    }
}

4. 푸시 알림 보내기

이제 앱에서 푸시 알림을 보낼 준비가 되었습니다. Firebase 콘솔로 돌아가서 푸시 알림을 보낼 대상을 선택하고 메시지를 작성합니다. 예를 들어, 특정 사용자에게 알림을 보내려면 사용자에게 할당된 FCM 토큰을 사용하여 직접 푸시 알림을 보낼 수 있습니다.

import FirebaseMessaging

func sendPushNotification(to token: String, title: String, body: String) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString: [String : Any] = [
        "to" : token,
        "notification" : [
            "title" : title,
            "body" : body,
        ],
        "data" : [
            "user" : "test_user_id",
        ]
    ]
    
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("key=YOUR_SERVER_KEY", forHTTPHeaderField: "Authorization")
    
    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        do {
            if let jsonData = data {
                if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: AnyObject] {
                    NSLog("Received data:\n\(jsonDataDict))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
}

이제 sendPushNotification 함수를 사용하여 특정 사용자에게 푸시 알림을 보낼 수 있습니다. token은 앱에서 얻은 FCM 토큰이며, titlebody는 알림의 제목과 내용입니다.

이렇게하면 Swift에서 푸시 알림을 사용하여 소셜 미디어 알림을 제공할 수 있습니다. Firebase를 사용하여 앱에 푸시 알림을 통합하는 것은 매우 간단하며, 더 많은 기능을 추가할 수 있습니다. reference: Firebase 푸시 알림 가이드