0

Dans mon application, j'utilise Firebase pour recevoir une notification mais j'ai un problème: lorsque j'envoie une notification depuis la console Firebase j'entends seulement la vibration de la notification et je peux voir le corps du message dans le journal. Je ne peux pas afficher la notification de bannière avec le corps du message en tant que texte et une icône. Je suis le guide officiel de here mais cela ne fonctionne pas.Firebase notification

Ceci est mon AppDelegate:

import UIKit 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

var window: UIWindow? 


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
     application.registerForRemoteNotifications() 

    FIRApp.configure() 

    // Add observer for InstanceID token refresh callback. 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), 
                name: kFIRInstanceIDTokenRefreshNotification, object: nil) 
    return true 
} 


func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
       fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 

    // TODO: Handle data of notification 
    print("This is userInfo -> \(userInfo)") 

    print("") 
    print(userInfo["notification"]!["body"]) 
    print("") 

    FIRMessaging.messaging().appDidReceiveMessage(userInfo) 
    completionHandler(.NoData) 


    NSLog("startLocalNotification") 
    var notification: UILocalNotification = UILocalNotification() 
    notification.fireDate = NSDate(timeIntervalSinceNow: 7) 
    notification.alertBody = userInfo["body"] as? String 
    notification.timeZone = NSTimeZone.defaultTimeZone() 
    notification.soundName = UILocalNotificationDefaultSoundName 
    notification.applicationIconBadgeNumber = 5 
    notification.alertAction = "open" 
    UIApplication.sharedApplication().scheduleLocalNotification(notification) 

} 

func tokenRefreshNotification(notification: NSNotification) { 
    let refreshedToken = FIRInstanceID.instanceID().token()! 
    print("InstanceID token: \(refreshedToken)") 

    // Connect to FCM since connection may have failed when attempted before having a token. 
    connectToFcm() 
} 

// [START connect_to_fcm] 
func connectToFcm() { 
    FIRMessaging.messaging().connectWithCompletion { (error) in 
     if (error != nil) { 
      print("Unable to connect with FCM. \(error)") 
     } else { 
      print("Connected to FCM.") 
     } 
    } 
} 
// [END connect_to_fcm] 


func applicationWillResignActive(application: UIApplication) { 

} 

func applicationDidEnterBackground(application: UIApplication) { 
    //Uncomment below to disconnect 
    //FIRMessaging.messaging().disconnect() 
    //print("Disconnected from FCM.") 
} 

func applicationWillEnterForeground(application: UIApplication) { 
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
} 

func applicationDidBecomeActive(application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
    connectToFcm() 
} 
} 

Ceci est mon ViewController:

import UIKit 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


@IBAction func handleLogTokenTouch(sender: UIButton) { 
    let token = FIRInstanceID.instanceID().token() 
    //  print("InstanceID token: \(token!)") 
    print("InstanceID token: \(token)") 

} 

@IBAction func handleSubscribeTouch(sender: UIButton) { 
    // [START subscribe_topic] 
    FIRMessaging.messaging().subscribeToTopic("/topics/news") 
    print("Subscribed to news topic") 
    // [END subscribe_topic] 
} 
} 

Comment puis-je faire pour montrer une notification dans une bannière?

Merci d'avance.

+1

Si votre application est fonctionnement ou Au premier plan, l'application appellera simplement la méthode déléguée, AUCUNE alerte ou bannière ne sera affichée. Alerte ou Bannière sera affiché si votre application est en arrière-plan ou est supprimée (pas au premier plan). Pour afficher une bannière pendant que l'application est en cours d'exécution, vous devez écrire votre propre code. Reportez-vous à [ce post] (http://stackoverflow.com/questions/4974512/uilocalnotification-isnt-working-at-all) –

+0

@DipenPanchasara si je tue mon application et que j'envoie une notification de la console rien n'apparaît sur mon appareil – Jigen

+0

Alert ou Banner est géré par OS lui-même, si vous voulez l'afficher commentez votre 'UILocalNotification', cela ne fonctionnera pas. Lorsque votre application n'est pas en cours d'exécution, le système traitera automatiquement la notification et affichera une alerte ou une bannière appropriée. Je crois que vous comprenez le contexte. –

Répondre

0

Vous devez gérer les notifications selon l'état de votre application comme suit, 1. Contexte: L'application affichera une notification selon les paramètres de l'utilisateur pour la notification. (Bannière, Alerte, etc.) 2. Forground: L'application n'affiche aucune notification lorsque l'application est au premier plan.

Si vous souhaitez informer l'utilisateur même lorsque l'application est au premier plan, vous devez personnaliser un peu votre code. ajouter du code suivant dans votre méthode didReceivedRemoteNotification

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
        fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 

     // TODO: Handle data of notification 
     print("This is userInfo -> \(userInfo)") 

     print("") 
     print(userInfo["notification"]!["body"]) 
     print("") 
     // I don't what the following two lines of code doing extactly 
     FIRMessaging.messaging().appDidReceiveMessage(userInfo) 
     completionHandler(.NoData) 
     // My code is as follows 
     if application.applicationState == UIApplicationState.Active { 
      //show a alert here 
     } 
    } 
+0

Je ne peux pas faire la bannière apparaît pour l'instant – Jigen

+0

ne vous a pas. – NSAnant

+0

Si vous voulez afficher la bannière personnalisée dans l'application lorsque l'utilisateur en utilisant l'application (App est au premier plan), puis il y a bannière 3ème partie disponible sur git/pod https://github.com/bryx-inc/BRYXBanner – NSAnant

0
you have to implement the message handling 

[START ios_10_message_handling]

@available(iOS 10, *) 
    extension AppDelegate : UNUserNotificationCenterDelegate { 

    // Receive displayed notifications for iOS 10 devices. 
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
           willPresent notification: UNNotification, 
           withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
     let userInfo = notification.request.content.userInfo 

     // With swizzling disabled you must let Messaging know about the message, for Analytics 
     Messaging.messaging().appDidReceiveMessage(userInfo) 
     // Print message ID. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 
     print(userInfo) 

     // Change this to your preferred presentation option 
    completionHandler([.alert, .badge, .sound]) 

     } 

    func userNotificationCenter(_ center: UNUserNotificationCenter, 
           didReceive response: UNNotificationResponse, 
           withCompletionHandler completionHandler: @escaping() -> Void) { 
     let userInfo = response.notification.request.content.userInfo 
     // Print message ID. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print(userInfo) 

     completionHandler() 

    } 
    } 
    // [END ios_10_message_handling] 
    extension AppDelegate : MessagingDelegate { 
    // [START refresh_token] 
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { 
    print("Firebase registration token: (fcmToken)") 
    } 

    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. 
    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true. 
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { 
    print("Received data message: (remoteMessage.appData)") 
    } 
    } 

Référence: https://github.com/firebase/quickstart-ios/issues/286#issuecomment-304978967

espoir pleinement il vous aide