[swift] SwifterSwift를 사용하여 앱의 알림 및 푸시 알림 구현하기

알림과 푸시 알림은 iOS 앱에서 중요한 기능 중 하나입니다. 사용자에게 메시지와 업데이트를 전달하는 강력한 도구입니다. 이 기능을 구현하기 위해 SwifterSwift라는 유용한 라이브러리를 사용할 수 있습니다.

SwifterSwift는 Swift로 작성된 다양한 유틸리티 클래스와 확장을 제공하여 개발자가 앱을 간편하게 구현할 수 있도록 도와줍니다. 이 라이브러리는 알림 및 푸시 알림을 처리하는 몇 가지 유틸리티 클래스와 확장을 제공합니다.

1. SwifterSwift 추가하기

SwifterSwift를 프로젝트에 추가하기 위해 먼저 공식 GitHub 저장소에서 SwifterSwift를 다운로드합니다.

다운로드한 파일을 프로젝트에 추가한 후, Xcode에서 프로젝트 파일의 타겟을 선택한 다음 “Build Phases” 탭으로 이동합니다. “Link Binary With Libraries” 섹션에서 “+” 버튼을 클릭하고 SwifterSwift.framework를 추가합니다.

2. 알림 및 푸시 알림 구현하기

SwifterSwift를 사용하여 알림 및 푸시 알림을 구현하는 방법에 대해 알아보겠습니다.

2.1 알림 요청 (Notification Request) 생성하기

앱에서 알림을 보내려면 사용자에게 알림을 요청해야 합니다. 다음 코드는 알림 요청을 생성하는 방법을 보여줍니다.

import SwifterSwift
import UserNotifications

let notificationCenter = UNUserNotificationCenter.current()

notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    if granted {
        // 사용자가 알림 요청을 승인했을 때
    } else {
        // 사용자가 알림 요청을 거부했을 때
    }
}

위 코드에서는 SwifterSwift의 notificationCenter 객체를 통해 requestAuthorization(options:completionHandler:) 메서드를 호출하여 알림 요청을 생성합니다. 사용자가 알림을 승인하거나 거부한 후의 결과는 completion handler를 통해 처리할 수 있습니다.

2.2 알림 생성하기

앱에서 사용자에게 알림을 보내기 위해서는 알림 객체를 생성해야 합니다. 다음 코드는 알림 객체를 생성하고 이를 사용하여 알림을 보내는 방법을 보여줍니다.

import SwifterSwift
import UserNotifications

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

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

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

notificationCenter.add(request) { error in
    if let error = error {
        // 알림을 보내는 동안 오류가 발생했을 때
    } else {
        // 알림이 성공적으로 보내졌을 때
    }
}

위 코드에서는 UNMutableNotificationContent 객체를 사용하여 알림의 제목(title), 내용(body), 사운드(sound)를 설정합니다. 그리고 UNTimeIntervalNotificationTrigger 객체를 사용하여 알림이 특정 시간 간격으로 반복되지 않도록 설정합니다. 마지막으로 UNNotificationRequest 객체를 생성한 후, notificationCenteradd(_:withCompletionHandler:) 메서드를 호출하여 알림을 보냅니다.

2.3 푸시 알림 생성하기

푸시 알림을 생성하는 방법도 알아보겠습니다. 푸시 알림은 원격 서버에서 알림을 보내는 기능이므로, 푸시 서비스를 사용해야 합니다. 대표적으로 Firebase, OneSignal 등이 있습니다. 이 예시에서는 Firebase를 사용하여 푸시 알림을 생성하는 방법을 보여줍니다.

먼저 Firebase 콘솔에서 앱을 등록한 후, Firebase SDK를 프로젝트에 추가합니다. 그리고 다음과 같이 didFinishLaunchingWithOptions 메서드 내에서 Firebase를 초기화합니다.

import SwifterSwift
import Firebase

FirebaseApp.configure()

Firebase를 초기화한 후, 다음과 같이 푸시 알림을 설정합니다.

import SwifterSwift
import FirebaseMessaging

extension AppDelegate: UNUserNotificationCenterDelegate, MessagingDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:          [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
        // Remote notification
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            // Request authorization
            }
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types:                               [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        }
        
        // Firebase
        Messaging.messaging().delegate = self
        
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("Device Token: \(deviceTokenString)")
        
        // Firebase 푸시 알림에 디바이스 토큰 등록
        Messaging.messaging().apnsToken = deviceToken
    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase Registration Token: \(fcmToken)")
        
        // 푸시 서버에 등록하는 로직 추가
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print("Received notification userInfo: \(userInfo)")
        
        // 푸시 알림 처리 로직 추가
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications with error: \(error.localizedDescription)")
    }
}

위 코드에서는 AppDelegate를 확장하여 Firebase와 푸시 알림을 처리하는 메서드를 구현합니다. didFinishLaunchingWithOptions에서는 알림 요청을 생성하고, Firebase 및 푸시 서버와의 통신을 설정합니다. didRegisterForRemoteNotificationsWithDeviceToken에서는 디바이스 토큰을 등록하고, messaging(_:didReceiveRegistrationToken:)에서는 Firebase 등록 토큰을 받아옵니다. didReceiveRemoteNotification에서는 푸시 알림을 처리하고, didFailToRegisterForRemoteNotificationsWithError에서는 등록 실패 시 에러를 처리합니다.

SwifterSwift를 사용하여 iOS 앱에서 알림과 푸시 알림을 구현하는 방법을 알아보았습니다. SwifterSwift는 강력한 유틸리티 클래스와 확장을 제공하여 개발자가 앱을 빠르게 개발할 수 있도록 도와줍니다. 이러한 도구들을 활용하여 앱을 개선하고 사용자에게 더 좋은 경험을 제공하세요.

참고 자료: