I am trying to implement FCM in my Application. I have followed the Documentation https://firebase.google.com/docs/ios/setup and created APN'S key and installed the pod files also.
- Firebase
- Firebase/Messaging
Now problem is I am getting data in below method:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}
But I am not getting notification and my UNUserNotification Methods are also not getting called.
Below is my code:
import UIKit
import Google
import GoogleSignIn
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//FireBase
let filePath = Bundle.main.path(forResource: "GoogleService-Info_Firebase", ofType: "plist")
let options = FIROptions(contentsOfFile: filePath)
//registerForPushNotifications()
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_,_ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
//application.registerForRemoteNotifications()
//UNUserNotificationCenter.current().delegate = self
application.registerForRemoteNotifications()
FIRApp.configure(with : options!)
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
}
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
if let refreshToken = FIRInstanceID.instanceID().token() {
Helper.sharedInstance.Print(refreshToken as AnyObject)
Helper.sharedInstance.userDefault.set("\(refreshToken)", forKey: AssessNowKyes.pushToken)
}
//Connect to FCM
connectToFcm()
}
//START connect_to_fcm
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
Helper.sharedInstance.Print("Unable to connect with FCM. \(String(describing: error))" as AnyObject)
} else {
Helper.sharedInstance.Print("Connected to FCM." as AnyObject)
}
}
}
}
//MARK :- Notification
extension AppDelegate {
//Request for Notifications
func registerForPushNotifications() {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
FIRMessaging.messaging().remoteMessageDelegate = self
//Helper.sharedInstance.Print("Permission granted: \(granted)" as AnyObject)
if granted == false {
// Helper.sharedInstance.Print("Permission granted: False in Loop" as AnyObject)
}
}
}
else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
}
//User Notification
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Play sound and show alert to the user
completionHandler([.alert,.sound])
}
//Recieve response
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// Determine the user action
switch response.actionIdentifier {
case UNNotificationDismissActionIdentifier:
print("Dismiss Action")
case UNNotificationDefaultActionIdentifier:
Helper.sharedInstance.Print(response.notification.request.content.userInfo as AnyObject)
/*if true == (response.notification.request.content.title).contains("Traffic") {
}
else if (response.notification.request.content.userInfo["type"] as? String)?.contains("Reminder") == true {
}
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [response.notification.request.identifier])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [response.notification.request.identifier])*/
default:
Helper.sharedInstance.Print("Unknown action" as AnyObject)
}
completionHandler()
}
}.
//MARK :- FCM DidRegisterRemoteNotificationWithDeviceToken
extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//FIRMessaging.messaging().
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .sandbox)
Helper.sharedInstance.Print(deviceToken as AnyObject)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Helper.sharedInstance.Print("Unable to register for remote notifications: \(error.localizedDescription)" as AnyObject)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
//Helper.sharedInstance.localNotificationTrigger(title: userInfo["title"]! as! String, body: userInfo["message"]! as! String, identifier: userInfo["gcm.message_id"]! as! String)
//0:1504338754994223%0dc014bc0dc014bc
// Print message ID.
/*if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}*/
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
Any issue with device or any other thing I am missing? Why I am not getting notification and why UNUserNotification is not working?