Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Firebase的iOS推送通知_Ios_Swift_Firebase_Swift3_Firebase Cloud Messaging - Fatal编程技术网

Firebase的iOS推送通知

Firebase的iOS推送通知,ios,swift,firebase,swift3,firebase-cloud-messaging,Ios,Swift,Firebase,Swift3,Firebase Cloud Messaging,我有个问题,不知道是什么问题。我已将Firebase集成到我的应用程序中。在我升级到xCode 8.3和Swift3.1之前,一切都还不错 我在控制台中从FCM接收前台通知,但当我在后台甚至前台输入时 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler com

我有个问题,不知道是什么问题。我已将Firebase集成到我的应用程序中。在我升级到xCode 8.3和Swift3.1之前,一切都还不错

我在控制台中从FCM接收前台通知,但当我在后台甚至前台输入时

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
从未执行过,我无法处理通知

这是我从FCM收到的消息

[AnyHashable("from"): 1234456, AnyHashable("sender_name"): Driver, AnyHashable("type"): NEW_MESSAGE, AnyHashable("text"): text ;)]
在AppDelegate中,我有以下内容:

    import UIKit
import CoreData
import FBSDKCoreKit
import FBSDKLoginKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    var apiManagerFunc = ApiManager()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


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

            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        }

        application.registerForRemoteNotifications()


        if let options: NSDictionary = launchOptions as NSDictionary? {
            let remoteNotification = options[UIApplicationLaunchOptionsKey.remoteNotification]
            if let notification = remoteNotification {
                self.application(application, didReceiveRemoteNotification: notification as! [AnyHashable: Any], fetchCompletionHandler: { (result) in
                })
            }
        }

        // [START add_token_refresh_observer]
        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)
        // [END add_token_refresh_observer]

        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")

            connectToFcm()
        }

        return true
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        // Let FCM know about the message for analytics etc.
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)
        // handle your message
    }


    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        if application.applicationState == .active {

            let userInfoCheck = userInfo["type"] as! String
            if userInfoCheck == "LOCATION_REQUEST" {
                let valueCheck = UserDefaults.standard.value(forKey: "myLocationSwitchState") as! String
                if valueCheck == "on" {

                    self.showAlertAppDelegate(title: "", message: userInfo["text"] as! String, buttonTitle: "Ok", window: self.window!)
                    self.updateLocationToServer()
                    print("Shown")
                } else {
                    print(valueCheck)
                }
            } else {
                self.showAlertAppDelegate(title: "New Message", message: userInfo["text"] as! String, buttonTitle: "Ok", window: self.window!)
            }


        } else {

            let userInfoCheck = userInfo["type"] as! String
            if userInfoCheck == "LOCATION_REQUEST" {
                let valueCheck = UserDefaults.standard.value(forKey: "myLocationSwitchState") as! String
                if valueCheck == "on" {
                    scheduleLocalNotification(message: userInfo["text"] as! String)
                    print("Shown")
                    self.updateLocationToServer()
                } else {
                    print(valueCheck)
                }
            } else {
                scheduleLocalNotification(message: userInfo["text"] as! String)
            }

        }
        // Print full message.
        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }

    func showAlertAppDelegate(title : String,message : String,buttonTitle : String,window: UIWindow){
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
        window.rootViewController?.present(alert, animated: true, completion: nil)
    }

    func scheduleLocalNotification(message: String) {

        // create a corresponding local notification
        let notification = UILocalNotification()

        notification.alertBody = message

        // play default sound
        notification.soundName = UILocalNotificationDefaultSoundName

        // assign a unique identifier to the notification so that we can retrieve it later
        notification.userInfo = ["UUID": UUID().uuidString]

        notification.category = "XXXXXXXXXXXXXXX"

        UIApplication.shared.scheduleLocalNotification(notification)
    }

    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
        print(notification)
    }

    // [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 {
                print("Unable to connect with FCM. \(String(describing: error))")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    // Successful registration and you have a token. Send the token to your provider, in this case the console for cut and paste.
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)

        print("Successful registration. Token is:")
        print(tokenString(deviceToken))
    }


    // Failed registration. Explain why.
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }


    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

        return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)

    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        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()
        FBSDKAppEvents.activateApp()
        FIRMessaging.messaging().connect { error in
            print(error as Any)
        }
    }

@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
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        // Change this to your preferred presentation option
        completionHandler(.badge)
    }

    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]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {

        print(remoteMessage.appData)
    }
}
// [END ios_10_data_message_handling]

这背后没有错误。只是,除非点击通知,否则不会调用此方法

这可能是APNs证书的问题。尝试打印FirebaseInstanceId令牌,并尝试将消息发送到该特定托克。您可能会在send API中收到更清晰的错误消息。