无法通过FCM从后端接收推送通知

时间:2017-02-21 14:37:47

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

快速简介,我已经开发了适用于iOS和Android的应用程序,他们共享相同的数据库,并且我已经在两个项目中实施了Firebase,根据Google 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上接收消息。

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,其背后的原因是iPhone和Android的有效载荷格式不同。 如果有效载荷格式不包含"通知"密钥,您将不会在iPhone上收到任何通知。

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

其他明智地创建相同的有效载荷,其中包含"通知"和"数据"按键如下。

{   "消息":{     "令牌":" bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1 ...&#34 ;,     "通知":{       "标题":"推标题",       " body":"消息正文"     },     "数据" :{       "尼克" :"尼克",       "客房" :"房间"     }   } }

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

相关问题