HomeArtTechHackBlockchain
ONLINE ·
Index
/
Technology
/
Article

บันทึก การทำ Firebase Messaging ด้วย Golang และ Config ให้ใช้งานบน iOS

Operator
Khomkrid Lerdprasert
Filed
November 26, 2021
Channel
Technology
Read
~1 min
บันทึก การทำ Firebase Messaging ด้วย Golang และ Config ให้ใช้งานบน iOS

บันทึก การทำ Firebase Messaging ด้วย Golang และ Config ให้ใช้งานบน iOS

เริ่มจากเราจะมาสร้าง project ios ไว้เทสรับ notification จาก firebase cloud messaging กัน ด้วยการไปตั้งชื่อ bundle ต่างๆให้เรียบร้อย

bundle identifer
bundle identifer

จากนั้นเราจะทำการ login เข้าไป set apple identifier key ที่ https://developer.apple.com

key identifer
key identifer

จากนั้น download key มันลงมาเก็บไว้ แล้วไปที่ firebase เข้าไปที่ project setting ของเรา ทำการ config ios app ใหม่ และตั้งชื่อ bundle identifer ให้ตรงกับ ios ของเรา

download plist
download plist

ต่อไปเราจะเอา key ที่ download มา เอาไป upload ใส่ firebase ของเรา และทำการใส่ค่า key และ team id ลงไป

add apple key
add apple key

จากนั้นเราจะไปที่ xcode แล้วทำการ add Swift package ของ firebase ลงไป

add firebase repo
add firebase repo

firebase dependencies
firebase dependencies

จากนั้นเราจะลาก plist ที่เรา download จาก firebase มาใน xcode project

add plist
add plist

เมื่อเรา add plist แล้ว เราจะ copy REVERSE_CLIENT_ID จาก google service มาใส่ใน url type

add plist
add plist

url type
url type

ต่อมาเราจะทำ AppDelegate ใน Swift เพื่อให้รองรับ Firebase Cloud Messaging

//
// TestFCMApp.swift
// TestFCM
//
// Created by Aofiee on 25/11/2564 BE.
//
import SwiftUI
import Firebase
@main
struct TestFCMApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
//Init
class AppDelegate: NSObject,UIApplicationDelegate {
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
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,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
-> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error){
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict: [String: String] = ["token": fcmToken ?? ""]
print(dataDict)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
Messaging.messaging().appDidReceiveMessage(userInfo)
// Change this to your preferred presentation option
completionHandler([[.banner,.badge,.sound]])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
}

จากนั้นเราจะทำการ code บน go กันให้ส่ง message ไปยัง firebase cloud messaging กันดังนี้ โดยเราจะไปดึง registration_token จาก table user ที่ทำการ ติดตั้ง app ios ที่เราทำไว้เมื่อกี้ และทำการส่งข้อความผ่าน MulticastMessage เพื่อส่งให้ผู้ใช้งานหลายคนพร้อมกัน ผ่าน firebase cloud messaging ไปยัง มือถือที่ติดตั้ง application ไว้อีกที ก็เป็นอันเรียบร้อย

func (c *contentRepository) SendNotification(content *[]models.Content) error {
var users []models.Users
if err := c.conn.Where("registration_token != ''").First(&users).Error; err != nil {
return err
}
var tokens []string
for _, user := range users {
tokens = append(tokens, user.RegistrationToken)
}
for _, ct := range *content {
var summary string
summary = strip.StripTags(ct.Content)
if len(ct.Content) > 255 {
summary = strip.StripTags(ct.Content[:255])
}
ctx := context.Background()
message := &messaging.MulticastMessage{
Notification: &messaging.Notification{
Title: ct.Title,
Body: summary,
},
Tokens: tokens,
}
br, err := c.client.SendMulticast(ctx, message)
if err != nil {
log.Println(err)
}
if br.FailureCount > 0 {
var failedTokens []string
for idx, resp := range br.Responses {
if !resp.Success {
failedTokens = append(failedTokens, tokens[idx])
}
}
log.Printf("List of tokens that caused failures: %v\n", failedTokens)
}
err = c.SetSendNotificationCompleted(&ct)
if err != nil {
return err
}
}
return nil
}

◎ Tags

##Go lang##Firebase##Swift
Khomkrid Lerdprasert
Operator

Khomkrid Lerdprasert

Technical Lead — building AI-powered platforms, omni-channel chat systems, and telemedicine solutions with Go, Next.js & clean architecture. 20+ years shipping software from crypto wallets to e-learning systems. Bangkok-based. Writes code late at night, brews beer on weekends.

GithubInstagram
Previous · transmission
บันทึก การทำ Swaggo บน go fiber จ่ะ
Next · transmission
Docker compose ทำ mongodb มาเชื่อมต่อ กับ golang
Metadata
Channel
Technology
Filed
November 26, 2021
Read
~1 min
Language
TH / EN
Transmit

Related

สร้าง Key pair เพื่อทำการ signing document signature ด้วย Go lang
Khomkrid Lerdprasert
March 13, 2024
1 min
aofiee.dev
signal / noise / code · craft
© 2019 – 2026, Khomkrid Lerdprasert.
All transmissions logged.
No newsletter. No profiling. Cookies require consent.
PGP · 7F3D 2024 A21E B584 · 0x7F3D
Channels
  • Art & Culture
  • Technology
  • Hack 101
  • Blockchain 101
  • Archive / All posts
— END OF TRANSMISSION —
// powered by curiosity, coffee, & wuxia
BKK · 13°45′N · 100°30′E