Я реализовал FirebaseCloudMessaging
, получая notifications
, когда приложение находится в Background
, но когда я устанавливаю свежее приложение willPresent
и didReceive
Уведомление delegate
не вызываются через 30-35 минут, оно начинает звонить.
Это происходит только тогда, когда я устанавливаю приложение, удаляя старое.
Вот мой код, вы можете проверить, где я ошибся
import UIKit
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register for push notification
self.registerForNotification()
FirebaseApp.configure()
Messaging.messaging().delegate = self
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
//MARK: - Register For RemoteNotification
func registerForNotification() {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { granted, error in }
UIApplication.shared.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
#if DEVELOPMENT
Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
#else
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
#endif
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
debugPrint("Unable to register for remote notifications: \(error.localizedDescription)")
}
//MARK: - UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
debugPrint(userInfo)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
debugPrint(userInfo)
completionHandler([.badge, .alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print(userInfo)
completionHandler()
}
}
extension AppDelegate: MessagingDelegate {
//MARK: - MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print(fcmToken)
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
Спасибо за помощь
через 30 минут после установки приложения. Я получаю уведомление, когда приложение находится в фоновом режиме. процесс регистрации прошел нормально.
Я имею в виду, что установить приложение недостаточно. Вы должны запустить его, чтобы вызвать registerForNotification(). И пользователь должен принять, когда появится предупреждение о запросе разрешения.
Это происходит, даже если вы отправляете уведомление вручную из консоли Firebase?
@Gabriel, когда приложение находится в фоновых уведомлениях, это означает, что я вызвал функцию registerForNotification(), а также разрешил разрешение. Благодарю.
@mohit Да, я пробовал с push-уведомления и с консоли firebase, возникает одна и та же проблема.
@HarshadPipaliya тот же код у меня работает нормально, даже если я меняю последовательность функций, я все равно получаю толчок. Удача на вашей стороне?
Нет, все равно не работает. К вашему сведению, я добавил GLNotificationBar и push-уведомление Intercom, есть ли с этим какие-либо проблемы?
Замените код функции registerForNotification на этот. Может быть, это поможет
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (isAllow, error) in
if isAllow {
Messaging.messaging().delegate = self
}
}
UIApplication.shared.registerForRemoteNotifications()
Когда пользователь разрешит уведомление, будет вызван этот метод делегата
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print(fcmToken)
}
при нажатии на уведомление
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//when notification is tapped
}
Этот метод будет вызываться, когда приложение находится на переднем плане.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//this method is called when notification is about to appear in foreground
completionHandler([.alert, .badge, .sound]) // Display notification as
}
@HarshadPipaliya .. может быть, это сработает .. Напишите FirebaseApp.configure () перед регистрацией для получения уведомления.. Также проверьте, запускаете ли вы свое приложение во второй раз, когда оно сработало или нет?
30 минут после установки приложения? Или через 30 минут после запуска приложения? Я полагаю, вы знаете, что приложение должно зарегистрироваться для получения push-уведомлений, чтобы создать новый токен.