didRegisterForRemoteNotificationsWithDeviceToken() 不会发送到react-native

问题描述 投票:0回答:1

我试图避免使用奇怪的库或价格过高的服务(例如 Azure)或不合规的服务(例如 Firebase)来向我的应用程序发送通知。因此,我决定构建自己的本机模块来做到这一点,但我在 Swift 方面的技能仍处于起步阶段,我有点坚持这一点:

所以基本上我这样做是为了在获得同意后注册通知:


import UserNotifications

@objc(PushNotificationManager)
class PushNotificationManager: NSObject, UNUserNotificationCenterDelegate {
  
  private var deviceToken: String?
  private var callback: RCTResponseSenderBlock?
  
  @objc static func requiresMainQueueSetup() -> Bool {
    return true
  }

@objc func registerForPushNotifications(_ callback: @escaping RCTResponseSenderBlock) {
    DispatchQueue.main.async {
      UIApplication.shared.registerForRemoteNotifications()
      self.callback = callback
    }
  }

@objc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    self.deviceToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device token set: \(String(describing: self.deviceToken))")
    self.callback?([NSNull(), self.deviceToken])
  }

  @objc func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register for remote notifications with error: \(error)")
    self.callback?([error.localizedDescription, NSNull()])
  }

然后在react-native中这样:

  if (Platform.OS === 'ios') {
            console.log("get permission")
            PushNotificationManager.requestPermission((error, granted) => {
                console.log("step 1")
                console.log(error)
                if (granted) {
                    console.log("step 2")
                    console.log("granted")
                    PushNotificationManager.registerForPushNotifications((error, token) => {
                        if (error) {
                            console.log("step 3")
                            console.log(error)
                        } else {
                            console.log("step 3")
                            console.log(token)
                        }
                    });
                }
            });
        }

但是,令牌或错误永远不会被记录。我的理解是 UIApplication.shared.registerForRemoteNotifications 是异步的,由于尝试同步运行,因此在 React-native 中返回未定义,但 AI 或谷歌搜索都无法修复它。

有什么建议吗?

ios swift react-native
1个回答
0
投票

didRegisterForRemoteNotificationsWithDeviceToken
didFailToRegisterForRemoteNotificationsWithError
功能必须进入您的
AppDelegate

它们不会在您的

PushNotificationManager
对象中被调用,因为系统不知道有关该类的任何信息。它只是您应用程序的一部分

© www.soinside.com 2019 - 2024. All rights reserved.