Files
suixinkan_uikit/suixinkan/Core/Push/PushNotificationManager.swift
汉秋 1b2637f0ee fix: 推送点击仅按 type 路由到收款页或消息中心。
对齐后端消息类型约定,去掉 route/uri 等兼容字段,并补充联调日志与单测。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-22 18:20:36 +08:00

423 lines
16 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import UIKit
import UserNotifications
/// App 便
@MainActor
protocol ApplicationIconBadgeSetting: AnyObject {
///
func setBadgeCount(_ count: Int) async
}
/// 使 UserNotifications App
@MainActor
final class SystemApplicationIconBadgeSetter: ApplicationIconBadgeSetting {
///
static let shared = SystemApplicationIconBadgeSetter()
private init() {}
func setBadgeCount(_ count: Int) async {
do {
try await UNUserNotificationCenter.current().setBadgeCount(max(count, 0))
} catch {
#if DEBUG
print("Update application icon badge failed: \(error.localizedDescription)")
#endif
}
}
}
/// SDK 便使
@MainActor
protocol PushSDKProviding: AnyObject {
/// APNs
func initialize(launchOptions: [UIApplication.LaunchOptionsKey: Any]?, isProduction: Bool)
///
func requestAuthorization(delegate: JPUSHRegisterDelegate)
/// APNs Device Token
func registerDeviceToken(_ deviceToken: Data)
/// Registration ID
func fetchRegistrationID(completion: @escaping (Int32, String?) -> Void)
}
/// `@Sendable`
private final class RegistrationIDCompletionBox: @unchecked Sendable {
let completion: (Int32, String?) -> Void
init(completion: @escaping (Int32, String?) -> Void) {
self.completion = completion
}
}
/// SDK AppKey
@MainActor
final class JPushSDKAdapter: PushSDKProviding {
private static let appKey = "194a633c2a6b79c2f1033c40"
private static let channel = "App Store"
/// SDKDebug Release
func initialize(launchOptions: [UIApplication.LaunchOptionsKey: Any]?, isProduction: Bool) {
JPUSHService.setup(
withOption: launchOptions,
appKey: Self.appKey,
channel: Self.channel,
apsForProduction: isProduction
)
#if DEBUG
JPUSHService.setDebugMode()
#else
JPUSHService.setLogOFF()
#endif
}
/// alertbadgesound
func requestAuthorization(delegate: JPUSHRegisterDelegate) {
let entity = JPUSHRegisterEntity()
entity.types = 1 | 2 | 4
JPUSHService.register(forRemoteNotificationConfig: entity, delegate: delegate)
}
/// APNs Device Token
func registerDeviceToken(_ deviceToken: Data) {
JPUSHService.registerDeviceToken(deviceToken)
}
/// Registration ID
func fetchRegistrationID(completion: @escaping (Int32, String?) -> Void) {
let box = RegistrationIDCompletionBox(completion: completion)
JPUSHService.registrationIDCompletionHandler { resultCode, registrationID in
box.completion(resultCode, registrationID)
}
}
}
/// Registration ID
@MainActor
final class PushNotificationManager: NSObject {
///
static let shared = PushNotificationManager()
///
private enum Key {
static let registrationID = "key_jpush_registration_id"
static let uploadedRegistrationIDSuffix = "jpush_uploaded_registration_id"
}
private let sdk: any PushSDKProviding
private let api: any PushRegistrationServing
private let appStore: AppStore
private let defaults: UserDefaults
private let router: any PushRouting
private let applicationIconBadgeSetter: any ApplicationIconBadgeSetting
private var isInitialized = false
private var didRequestAuthorization = false
private var uploadTask: Task<Void, Never>?
private var queuedForcedUpload = false
private var isFetchingRegistrationID = false
private var queuedForcedFetch = false
/// 使
init(
sdk: (any PushSDKProviding)? = nil,
api: (any PushRegistrationServing)? = nil,
appStore: AppStore = .shared,
defaults: UserDefaults = .standard,
router: (any PushRouting)? = nil,
applicationIconBadgeSetter: (any ApplicationIconBadgeSetting)? = nil
) {
self.sdk = sdk ?? JPushSDKAdapter()
self.api = api ?? NetworkServices.shared.pushAPI
self.appStore = appStore
self.defaults = defaults
self.router = router ?? PushRouteCoordinator.shared
self.applicationIconBadgeSetter = applicationIconBadgeSetter ?? SystemApplicationIconBadgeSetter.shared
super.init()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// Scene
func attach(window: UIWindow) {
router.attach(window: window)
}
/// SDK
func initializeIfPrivacyAccepted(
launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) {
guard appStore.session.privacyAgreementAccepted, !isInitialized else { return }
isInitialized = true
sdk.initialize(launchOptions: launchOptions, isProduction: Self.isProductionBuild)
observeJPushNetworkLogin()
refreshRegistrationID(forceUpload: false)
}
///
func handleLoginCompleted() {
initializeIfPrivacyAccepted()
guard isInitialized, appStore.session.isLoggedIn else { return }
if !didRequestAuthorization {
didRequestAuthorization = true
sdk.requestAuthorization(delegate: self)
}
bindCurrentAccount()
}
///
func handleAccountSwitched() {
guard appStore.session.isLoggedIn else { return }
bindCurrentAccount()
}
/// 退
func handleLogout() {
uploadTask?.cancel()
uploadTask = nil
queuedForcedUpload = false
router.resetPendingRoute()
Task { await updateApplicationIconBadgeCount(0) }
}
/// App Icon
func updateApplicationIconBadgeCount(_ count: Int) async {
await applicationIconBadgeSetter.setBadgeCount(max(count, 0))
}
/// App Registration ID
func retryPendingRegistrationUpload() {
guard appStore.session.isLoggedIn else { return }
uploadCachedRegistrationID(force: false)
refreshRegistrationID(forceUpload: false)
}
///
func routePendingNotificationIfPossible() {
router.routePendingIfPossible()
}
/// APNs Device Token
func handleDeviceToken(_ deviceToken: Data) {
guard isInitialized else { return }
sdk.registerDeviceToken(deviceToken)
refreshRegistrationID(forceUpload: false)
}
/// APNs
func handleRegistrationError(_ error: Error) {
#if DEBUG
print("JPush APNs registration failed: \(error.localizedDescription)")
#endif
}
///
func handleNotificationTap(
payload: PushPayload,
requestIdentifier: String
) {
router.handle(
destination: payload.destination,
requestIdentifier: requestIdentifier
)
}
/// Scene
func handleNotificationResponse(_ response: UNNotificationResponse) {
let userInfo = response.notification.request.content.userInfo
Self.logReceivedPush(userInfo, source: "tap(cold-start)")
JPUSHService.handleRemoteNotification(userInfo)
handleNotificationTap(
payload: PushPayload(userInfo: userInfo),
requestIdentifier: response.notification.request.identifier
)
}
///
func handleRemoteNotification(_ userInfo: [AnyHashable: Any]) {
Self.logReceivedPush(userInfo, source: "background")
JPUSHService.handleRemoteNotification(userInfo)
NotificationCenter.default.post(name: NotificationName.unreadMessageCountDidChange, object: nil)
}
/// payload 便
private nonisolated static func logReceivedPush(
_ userInfo: [AnyHashable: Any],
source: String
) {
#if DEBUG
let payloadText: String
let normalized = Dictionary(uniqueKeysWithValues: userInfo.compactMap { key, value in
(key as? String).map { ($0, value) }
})
if JSONSerialization.isValidJSONObject(normalized),
let data = try? JSONSerialization.data(
withJSONObject: normalized,
options: [.prettyPrinted, .sortedKeys]
),
let text = String(data: data, encoding: .utf8) {
payloadText = text
} else {
payloadText = String(describing: userInfo)
}
print("[Push] received (\(source)):\n\(payloadText)")
#endif
}
private func observeJPushNetworkLogin() {
NotificationCenter.default.addObserver(
self,
selector: #selector(handleJPushNetworkLogin),
name: .jpfNetworkDidLogin,
object: nil,
)
}
@objc private func handleJPushNetworkLogin() {
refreshRegistrationID(forceUpload: false)
}
private func refreshRegistrationID(forceUpload: Bool) {
guard isInitialized else { return }
queuedForcedFetch = queuedForcedFetch || forceUpload
guard !isFetchingRegistrationID else { return }
isFetchingRegistrationID = true
sdk.fetchRegistrationID { [weak self] resultCode, registrationID in
Task { @MainActor in
guard let self else { return }
let shouldForceUpload = self.queuedForcedFetch
self.queuedForcedFetch = false
self.isFetchingRegistrationID = false
guard resultCode == 0 else { return }
let normalized = registrationID?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !normalized.isEmpty else { return }
self.defaults.set(normalized, forKey: Key.registrationID)
self.upload(registrationID: normalized, force: shouldForceUpload)
}
}
}
private func uploadCachedRegistrationID(force: Bool) {
let registrationID = cachedRegistrationID
guard !registrationID.isEmpty else { return }
upload(registrationID: registrationID, force: force)
}
private func bindCurrentAccount() {
if cachedRegistrationID.isEmpty {
refreshRegistrationID(forceUpload: true)
} else {
uploadCachedRegistrationID(force: true)
refreshRegistrationID(forceUpload: false)
}
}
private var cachedRegistrationID: String {
defaults.string(forKey: Key.registrationID)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
}
private func upload(registrationID: String, force: Bool) {
guard appStore.session.isLoggedIn,
let uploadedKey = appStore.session.accountScopedKey(Key.uploadedRegistrationIDSuffix)
else { return }
if !force, defaults.string(forKey: uploadedKey) == registrationID {
return
}
if uploadTask != nil {
queuedForcedUpload = queuedForcedUpload || force
return
}
let accountScope = appStore.session.accountCachePrefix
uploadTask = Task { [weak self] in
guard let self else { return }
var succeeded = false
do {
try await self.api.registerJPushID(registrationID)
if self.appStore.session.accountCachePrefix == accountScope {
self.defaults.set(registrationID, forKey: uploadedKey)
}
succeeded = true
} catch is CancellationError {
// 退
} catch {
#if DEBUG
print("JPush Registration ID upload failed: \(error.localizedDescription)")
#endif
}
self.uploadTask = nil
let shouldForceAgain = self.queuedForcedUpload
self.queuedForcedUpload = false
if succeeded, shouldForceAgain {
self.uploadCachedRegistrationID(force: true)
}
}
}
private nonisolated static var isProductionBuild: Bool {
#if DEBUG
false
#else
true
#endif
}
}
extension PushNotificationManager: JPUSHRegisterDelegate {
/// UI
nonisolated func jpushNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (Int) -> Void
) {
let userInfo = notification.request.content.userInfo
Self.logReceivedPush(userInfo, source: "foreground")
JPUSHService.handleRemoteNotification(userInfo)
Task { @MainActor in
NotificationCenter.default.post(name: NotificationName.unreadMessageCountDidChange, object: nil)
}
let options: UNNotificationPresentationOptions = [.banner, .list, .sound, .badge]
completionHandler(Int(options.rawValue))
}
/// Actor
nonisolated func jpushNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
Self.logReceivedPush(userInfo, source: "tap")
JPUSHService.handleRemoteNotification(userInfo)
let payload = PushPayload(userInfo: userInfo)
let requestIdentifier = response.notification.request.identifier
Task { @MainActor [weak self] in
self?.handleNotificationTap(
payload: payload,
requestIdentifier: requestIdentifier
)
}
completionHandler()
}
///
nonisolated func jpushNotificationCenter(
_ center: UNUserNotificationCenter,
openSettingsFor notification: UNNotification
) {}
///
nonisolated func jpushNotificationAuthorization(
_ status: JPAuthorizationStatus,
withInfo info: [AnyHashable: Any]?
) {}
}