【问题标题】:Unable to receive Push Notification from backend via FCM无法通过 FCM 从后端接收推送通知
【发布时间】:2017-02-21 14:37:47
【问题描述】:

简短地说,我已经为 iOS 和 Android 开发了一个应用程序,它们共享同一个数据库,并且根据 Google Firebase 教程,我已经在两个项目上实现了 Firebase,但是当我的后端发送推送通知时,我成功收到了通知在 Android 上,但我的 iOS 设备或控制台中没有显示任何内容。

这是我的后端代码(PHP):

    $message = array('message' => 'Blood Donation alert ',
                 'mobile' => $rdmob,
                 'name' => $rdname,
                 'bt' => $rdbt,
                 'rh' => $rdrh,
                 'loclat' =>$rdloclat,
                 'loclon' =>$rdloclon,
                 'locdetails' =>$BD_R_loc_details);

sendMessageThroughGCM($tokens_arr, $message);






function sendMessageThroughGCM($registatoin_ids, $message)
{
    $url = 'https://android.googleapis.com/gcm/send';
    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,

    );
    define("GOOGLE_API_KEY", "AAAA3n_S2aE:APA91bFpFVn5XbhP_FeXXoZGkG9la94WTMsORZwKrzd-0sNKM8nbjM_E2jMcaAjaubMP11pgby4RFUllVAaUBcmkoOaOw7NG-Xa-JOhfY-UCq829Wa49yxw0IttAnSUge_P4Wmtg");
    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        'Content-Type: application/json'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    echo json_encode($fields['data']);
 }

后端响应:

"multicast_id":8083296270394010691,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1487685174974179%af466c60f9fd7ecd"},{"message_id":"0:1487685175118033%85bd0ba8f9fd7ecd"}]}

这是我的 iOS Appdelegate.swift:

    import UIKit
import MapKit
import GoogleMaps
import Firebase
import UserNotifications
import FirebaseMessaging
import FirebaseInstanceID

var gAPNS_Token: String?

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    let gcmMessageIDKey = "gcm.message_id"

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //GoogleMaps Setup
        GMSServices.provideAPIKey("AIzaSyAK0eCZr-V8DxbjjXcpZ549s")
        //GMSPlacesClient.provideAPIKey("AIzaSyAK0eCZr-V8DxbFeis")

        //Navigation bar customization
        let navigationBarAppearace = UINavigationBar.appearance()

        navigationBarAppearace.tintColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
        navigationBarAppearace.barTintColor = #colorLiteral(red: 0.8692382813, green: 0, blue: 0, alpha: 1)

        UIApplication.shared.statusBarStyle = .lightContent

        // change navigation item title color
        navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]

        // Register for remote notifications. This shows a permission dialog on first run, to
        // show the dialog at a more appropriate time move this registration accordingly.
        // [START register_for_notifications]
        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)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // [END register_for_notifications]
        FIRApp.configure()

        // [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]

        return true
    }

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

    // [START refresh_token]
    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

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

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
    // the InstanceID token.
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print(deviceTokenString)

        gAPNS_Token = deviceTokenString

        // With swizzling disabled you must set the APNs token here.
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    }

    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)

        if let aps = userInfo["aps"] as? NSDictionary {
            if let alert = aps["alert"] as? NSDictionary {
                if let message = alert["message"] as? NSString {
                    //Do stuff
                    print("%@", message);
                }
            } else if let alert = aps["alert"] as? NSString {
                //Do stuff
                print("Do stuff")
            }
        }

    }


    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // 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)


        if let aps = userInfo["aps"] as? NSDictionary {
            if let alert = aps["alert"] as? NSDictionary {
                if let message = alert["message"] as? NSString {
                    //Do stuff
                    print("%@", message);
                }
            } else if let alert = aps["alert"] as? NSString {
                //Do stuff
                print("Do stuff")
            }
        }

        completionHandler(UIBackgroundFetchResult.newData)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    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 active 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.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

// [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
        // 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([])
    }

    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 证书,我的应用成功获取了 APNS 令牌和 FCM 令牌。

- 只有我手动完成,iOS 才能成功接收通知,Firebase 控制台 -> 通知 -> 发送新通知(定位 iOS 应用程序)。

更新:

PHP 代码更新

    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,
   'priority' => 'high',

    );

我现在给消息分配了高优先级,但仍然无法在 iOS 上接收。

【问题讨论】:

标签: firebase notifications swift3 ios10 firebase-cloud-messaging


【解决方案1】:

我遇到了同样的问题,原因是 iPhone 和 Android 的有效负载格式不同。 如果有效载荷格式不包含“通知”键,您将不会在 iPhone 上收到任何通知。

请告诉您的后端 PHP 开发人员为 iOS 和 Android 应用程序创建单独的有效负载格式。

另外创建包含“通知”和“数据”键的相同有效负载,如下所示。

{ “信息”:{ “令牌”:“bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1 ...”, “通知”:{ "title":"推送标题", "body":"消息正文" }, “数据” : { “尼克”:“尼克”, “房间”:“房间” } } }

您可以参考以下链接了解有效载荷格式。 https://firebase.google.com/docs/cloud-messaging/concept-options

【讨论】:

  • 成功了。缺少通知键。添加后,它就像一个魅力。谢谢。