Прежде всего, я знаю, что уже есть несколько разговоров об этом. Но я не мог найти ответ, который решил бы мою проблему.
Я бы хотел, чтобы моё приложение-реактив запускалось, когда пользователь приходит из уведомления. На Android у меня нет проблем, триггер работает, когда приложение находится в фоновом режиме, на переднем плане или даже закрыто.
В iOS не могу понять почему, но триггер не работал, когда приложение закрыто.
Вот моя версия зависимостей:
- Реактор: 0,59,3
- реактивная база огня: 5.1.1
- xCode: 10,2
- база огня: 5.0.3
- firebase-admin: 5.12.0
В моем 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();
}
Все работает хорошо, за исключением случая, когда приложение закрыто, моя переменная messagesOpen всегда равна нулю.
Вот как я могу отправить уведомление:
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) { }
}
Я взял несколько примеров кода из своего исследования, но он все еще не работает.
Может ли кто-нибудь помочь мне понять, где моя ошибка? Было бы очень признателен, спасибо :)