0

私はiOSとAndroidのアプリを開発しました。それらは同じDBを共有しています.Google Firebaseのチュートリアルによれば、両方のプロジェクトでFirebaseを実装しました。 Androidで通知を正常に受信したプッシュ通知を送信しますが、iOSデバイスまたはコンソールに何も表示されません。ここで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']); 
} 

バックエンドの応答:

"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を持っています私のアプリはAPNSトークンとFCMトークンを正常に取得します。

- iOSは手動でFirebaseコンソール - >通知 - >新しい通知を送信する(iOSアプリケーションを対象とする)の場合にのみ通知を正常に受信します。

UPDATE:

PHPコード私は今、メッセージに高い優先度を割り当てられ、まだiOSの上でそれを受信することができませんしている

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

    ); 

を更新します。

+0

ペイロードに値が「高」に設定された 'priority'パラメータを追加できますか? '' priority '=>' high''のように。 –

+0

デフォルトの優先順位は、高い@ALです。 –

+0

Err。 [*デフォルトでは、 'notification'メッセージは優先度が高く、' data'メッセージは通常の優先度で送信されます。*](https://firebase.google.com/docs/cloud-messaging/http-server-ref #downstream-http-messages-json)。ペイロードに 'data'を使っています。 –

答えて

0

私は同じ問題を抱えていました。その理由は、iPhoneとAndroidのペイロードフォーマットが異なることです。 ペイロードフォーマットに「通知」キーが含まれていないと、あなたのiPhoneで通知を受け取ることはありません。

iOSとAndroidアプリケーション用に別々のペイロードフォーマットを作成するようにバックエンドPHP開発者に教えてください。

「通知」と「データ」キーの両方を含む同じペイロードを次のように作成します。

{ "メッセージ":{ "トークン": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1 ..."、 "通知":{ "タイトル": "タイトルプッシュ"、 "本体": "メッセージ本文" }、 "データ":{ "ニック": "ニック"、 "ルーム": "ルーム" }} }

あなたはペイロード形式については、以下のリンクを参照することができます。 https://firebase.google.com/docs/cloud-messaging/concept-options

関連する問題