未调用UNUserNotificationDelegate方法,并且通知未显示FCM

时间:2017-09-02 10:42:29

标签: ios firebase push-notification unusernotificationcenter

我正在尝试在我的应用程序中实现FCM。我已按照文档https://firebase.google.com/docs/ios/setup创建了APN&#S; S键并安装了pod文件。

  1. Firebase
  2. 火力地堡/消息
  3. 现在问题是我在下面的方法中获取数据:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
          FIRMessaging.messaging().appDidReceiveMessage(userInfo)
    }
    

    但我没有收到通知,我的UNUserNotification方法也没有被调用。

    以下是我的代码:

    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: - 通知

    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)
      }
    }
    

    设备或我遗失的任何其他问题?为什么我没有收到通知以及为什么UNUserNotification不起作用?

0 个答案:

没有答案