0

быстро, я разработал приложение для iOS и Android, у них есть одна и та же БД, и я применил Firebase для обоих проектов, согласно учебникам Google Firebase, но когда мой бэкэнд отправляет push-уведомление, я получаю уведомление на Android, но ничего не появляется на моем устройстве или консоли iOS.Не удалось получить Push-уведомление от бэкэнда через FCM

Вот мой бэкенд код (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']); 
} 

Backend ответ:

"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 ce rtificate, и мое приложение успешно получает токен APNS и токен FCM.

- iOS получает уведомление успешно, только если я сделал это вручную, Firebase Console -> Уведомление -> Отправить новое уведомление (приложение для таргетинга iOS).

UPDATE:

PHP код обновление

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

    ); 

Я назначен приоритет высокого к сообщению в настоящее время, и до сих пор не в состоянии получить его прошивку.

+0

Можете ли вы попробовать добавить параметр 'priority' со значением, установленным на' high' в вашей полезной нагрузке? Подобно '' priority '=>' high''. –

+0

приоритет по умолчанию - высокий @AL. –

+0

Err. [* По умолчанию сообщения «уведомление» отправляются с высоким приоритетом, а сообщения «данные» отправляются с нормальным приоритетом. *] (Https://firebase.google.com/docs/cloud-messaging/http-server-ref # вниз по течению от HTTP-сообщений-JSON). Вы используете «данные» в своей полезной нагрузке. –

ответ

0

Я столкнулся с такой же проблемой и причиной, что формат загрузки для iPhone и Android отличается. Если формат полезной информации не содержит ключа «уведомления», вы не получите уведомления на своем iPhone.

Просьба сообщить разработчику PHP для создания отдельного формата полезной информации для приложений iOS и Android.

Другие мудрые создают такую ​​же полезную нагрузку, которая содержит как ключи «уведомлений», так и «данные» следующим образом.

{ "сообщение": { "маркер": "bk3RNwTe3H0: CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1 ...", "уведомление": { "Название": "Нажмите название", "тело": "Тело сообщения" }, "данные": { "Ник": "Ник", "номер": "номер" }} }

Вы можете обратиться ссылку для формата полезной нагрузки. https://firebase.google.com/docs/cloud-messaging/concept-options

Смежные вопросы