0%

Firebase FCM 推播

Firebase FCM 推播

[TOC]

後台設定

以下操作是在完成Firebase專案設定情況下進行設定

至apple.develop下載發送推播需要的 APNs key(p8)

至Firebase 後台上傳金鑰

至專案設定的雲端通訊

上傳金鑰

Xcode 專案設定

至AppDelegate做以下設定

1
2
3
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

}

設置消息傳遞委託

必須先執行 FirebaseApp.configure() 再設定delegate,否則會crash

1
FirebaseApp.configure()
1
Messaging.messaging().delegate = self

註冊遠程通知

1
2
3
4
5
6
7
8
9
10
11
12
UNUserNotificationCenter.current().delegate = self

let options = UNAuthorizationOptions([.alert, .sound, .badge])
UNUserNotificationCenter.current().requestAuthorization(options: options, completionHandler: { granted, _ in
if granted {
//使用者同意
} else {
//使用者不同意
}
})

application.registerForRemoteNotifications()

取得FCM Token

此Token可以提供Firebase做單獨裝置的推播測試

1
2
3
4
5
6
7
8
9
10
11
12
13
//MARK: - MessagingDelegate

extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
}
}
}
}

使用Firebase後台測試

新增推播通知

  • 設定推播內容

  • 輸入FCM Token 可立即對該裝置做推播測試

  • 指定推播對象,可針對不同App做設定,也可根據使用者或訂閱的主題進行推播

  • 設定推播要發送的時間

  • 自定義資料

  • **點選審查後能多裝置發送推播 **

發送後並不會馬上收到推播,需等待數秒至一兩分鐘

tags: Firebase Swift 推播