首先,我知道已经有很多关于此的对话。但是我找不到解决我问题的答案。
我希望我的react-native应用程序在用户来自通知时触发。在Android上,当应用程序在后台,前景甚至关闭时,触发器都可以正常工作。
在iOS上,我不知道为什么,但是在关闭应用程序时,触发器不起作用。
这是我的依赖版本:
在我的 App.js 中,我注册了侦听器来处理通知操作。
handleNotificationClicked = notificationOpen => {
const { data } = notificationOpen.notification;
console.log('DATA NOTIF');
console.log(data);
setParam(data.title);
FCM.conditionalNavigate(data, data.title);
};
async createNotificationListeners() {
/* If app is in foreground */
this.notificationListener = firebase.notifications().onNotification(notification => {});
/* If app is in background */
this.notificationOpenedListener = firebase.notifications().onNotificationOpened(this.handleNotificationClicked);
/* If app is closed */
const notificationOpen = await firebase.notifications().getInitialNotification();
console.log('notificationOpen', notificationOpen);
if (notificationOpen) {
console.log('HERE please');
this.handleNotificationClicked(notificationOpen);
}
}
async componentDidMount() {
const { setCurrentRoute } = this.props;
const defaultRoute = NavigationService.initCurrentRoute();
setCurrentRoute({ route: defaultRoute });
await this.createNotificationListeners();
}
一切正常,除了关闭应用程序的情况之外,我的变量 notificationOpen 始终为空。
这是我发送通知的方式:
const sendMessage = async () => {
const message = {
notification: {
title,
body
},
data: {
title,
body
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#002559'
}
},
apns: {
payload: {
aps: {
badge: 0
}
}
},
topic
}
try {
console.info('index firestore message', message);
await admin.messaging().send(message);
} catch (err) {
console.error('sendMessage failed', err);
throw err;
}
};
我收到通知,但是当我单击它时,getInitialNotification()方法没有任何作用...
所以我认为问题出在我的本机代码上。
import Foundation
import UserNotifications
import Firebase
import FirebaseMessaging
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
let bridge = RCTBridge(delegate: self, launchOptions: launchOptions)
let rootView = RCTRootView(bridge: bridge, moduleName: "", initialProperties: nil)
rootView?.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1)
self.window = UIWindow(frame: UIScreen.main.bounds)
let rootViewController = UIViewController()
rootViewController.view = rootView
self.window?.rootViewController = rootViewController
self.window?.makeKeyAndVisible()
didFinishLaunching = true
Fabric.with([Crashlytics.self])
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().useMessagingDelegateForDirectChannel = true
Messaging.messaging().shouldEstablishDirectChannel = true
self.requestAuthorization(for: application, launchOptions: launchOptions)
RNSplashScreen.showSplash("LaunchScreen", inRootView: rootViewController.view)
return true
}
private func requestAuthorization(for application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey : Any]?) {
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()
}
// MARK: - Notifications extention
extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// iOS10+, called when presenting notification in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
NSLog("[UserNotificationCenter] applicationState: willPresentNotification: \(userInfo)")
//TODO: Handle foreground notification
completionHandler([.alert])
}
// iOS10+, called when received response (default open, dismiss or custom action) for a notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
NSLog("[UserNotificationCenter] applicationState: didReceiveResponse: \(userInfo)")
//TODO: Handle background notification
completionHandler()
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { }
}
我从研究中获得了一些代码示例,但仍然无法正常工作。
有人可以帮助我弄清楚我的错误在哪里吗?非常感谢,谢谢:)