❗️Apple Developer 계정을 구입한 분들만 Push Notification 을 사용할 수 있습니다.
import SwiftUI
import Firebase
import FirebaseMessaging
@main
struct SOCprojectUIApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// Configuring Firebase Push Notification...
// See my Full Push Notification Video...
// Link in Description...
class AppDelegate: NSObject, UIApplicationDelegate{
let gcmMessageIDKey = "gcm.message_id"
// 앱이 켜졌을 때
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// 파이어베이스 설정
FirebaseApp.configure()
// Setting Up Notifications...
// 원격 알림 등록
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOption: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOption,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// Setting Up Cloud Messaging...
// 메세징 델리겟
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
return true
}
// fcm 토큰이 등록 되었을 때
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
}
// Cloud Messaging...
extension AppDelegate: MessagingDelegate{
// fcm 등록 토큰을 받았을 때
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("토큰을 받았다")
// Store this token to firebase and retrieve when to send message to someone...
let dataDict: [String: String] = ["token": fcmToken ?? ""]
// Store token in Firestore For Sending Notifications From Server in Future...
print(dataDict)
}
}
// User Notifications...[AKA InApp Notification...]
@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
// 푸시 메세지가 앱이 켜져있을 때 나올떄
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
-> Void) {
let userInfo = notification.request.content.userInfo
// Do Something With MSG Data...
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler([[.banner, .badge, .sound]])
}
// 푸시메세지를 받았을 떄
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Do Something With MSG Data...
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler()
}
}
출처 : https://designcode.io/swiftui-advanced-handbook-push-notifications-part-2
처음 App 을 실행하면 알림에 관한 사용자 권한 허용 경고창이 뜨게되고 허용을 눌러주세요.