Moon

 · 25天 ago

Hotwire Native 深度解析:推送通知

原生推送通知比较复杂,因为需要正确处理很多环节。以下是我在 Hotwire 原生应用中实现原生推送通知的详细步骤。

移动应用的一大卖点就是推送通知。

有时,这就是我的客户需要应用程序而不是网站的原因  这是因为推送通知即时有效,而且比电子邮件或短信更能吸引用户参与。即使渐进式 Web 应用 (PWA) 最近得到了改进,原生应用仍然是发送可靠、及时通知的最佳方式。

遗憾的是,实现推送通知并非易事。它涉及诸多环节 ,而且所有环节都必须完美契合才能正常工作。这还没涉及到 Hotwire Native 特有的代码呢!

好消息是,您完全可以放心。过去十年间,我为数十款 Hotwire Native 应用添加了推送通知功能。我见证了需求的不断变化,并持续调整流程以适应新的需求。以下是使用 #Hotwire Native 为 iOS 和 Android 应用发送推送通知的最简洁方法。

在深入代码之前,让我们先来了解一下其中涉及的不同角色。

通过 APNs 和 FCM 推送通知

推送通知通过 Apple 推送通知服务 (#APNs) 发送到 iOS 设备,通过 Firebase 云消息传递 (FCM) 发送到 Android 设备。推送通知通过向这些服务发送 JSON 有效负载来触发。设备特定的通知令牌用于确定哪些用户会收到这些通知。

流程如下:

  1. 该设备提供一个唯一的通知令牌并将其发送到服务器。
  2. 后端服务器向 APNs/Firebase 发送包含令牌的有效负载。
  3. 设备接收来自 APNs/FCM 的推送通知。

对于 Hotwire Native,我经常会实现类似这样的功能:

  1. 通过桥接组件注册设备以接收推送通知:
class NotificationTokenComponent: BridgeComponent {
class var name: String { "notification-token" }

override func onReceive(message: Message) {
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
try await center.requestAuthorization(options: options)
UIApplication.shared.registerForRemoteNotifications()
}
}
  1. 通过 API 客户端向服务器 POST 令牌:
func register(_ token: String) async throws {
let url = rootURL.appending(path: “notification_tokens.json”)
var req = URLRequest(url: url)

req.httpMethod = "POST"
req.addValue("application/json", forHeader: "Content-Type")

let notificationToken = NotificationToken(token: token)
req.httpBody = try JSONEncoder().encode(notificationToken)

try await URLSession.shared.data(for: req)
}
  1. 通过 Action Push Native 将令牌持久化到新的 JSON 端点中:
class NotificationTokensController < ApplicationController
def create
ApplicationPushDevice.find_or_create_by!(
token: params[:token],
owner: Current.user
)
head :ok
end
end
  1. 向 APNs/FCM 发送通知:
ApplicationPushNotification.new(title: “A new notification!”)
.deliver_later_to(Current.user.application_push_devices)

想要了解具体方法? 付费部分包含:

  • 我遵循的这四个步骤就能让一切正常运行 
  • 一份清单,帮助您减少调试时间
  • #Rails#iOS#Android 应用的完整源代码

作者 Joe Masilotti

来源 https://newsletter.masilotti.com/p/hotwire-native-deep-dive-push-notifications