2017-09-29 1 views
3

Je suis très novice en matière de développement et je n'ai pas trouvé beaucoup de support de bout en bout sur ce sujet. J'ai fait ce que j'ai pu en utilisant la page d'aide Firebase. Je ne parviens pas à recevoir de notifications sur mes appareils iOS, mais FCM fonctionne parfaitement sur Android. Voici mon appdelegate de XcodeNotifications push dans iOS en utilisant Firebase et PHP

import UIKit 
import Firebase 
import FirebaseMessaging 
import UserNotifications 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { 

    var window: UIWindow? 


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     UIApplication.shared.applicationIconBadgeNumber = 0 
     // Override point for customization after application launch. 
     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) 
      UIApplication.shared.registerUserNotificationSettings(settings) 
      UIApplication.shared.registerForRemoteNotifications() 
     } 

     application.registerForRemoteNotifications() 

     FirebaseApp.configure() 
     return true 
    } 

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
     let token1 = Messaging.messaging().fcmToken 
     print("FCM token: \(token1 ?? "")") 
     var request = URLRequest(url: URL(string: "http://www.myurl.com/register.php")!) 
     request.httpMethod = "POST" 
     let postString = "Token="+token1! 
     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(String(describing: error))") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(String(describing: response))") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      print("responseString = \(String(describing: responseString))") 
     } 
     task.resume() 
    } 

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
     print("Registration failed!") 
    } 

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

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

    @available(iOS 10.0, *) 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) { 

     // custom code to handle push while app is in the foreground 
     print("Handle push from foreground\(notification.request.content.userInfo)") 

     let dict = notification.request.content.userInfo["aps"] as! NSDictionary 
     let d : [String : Any] = dict["alert"] as! [String : Any] 
     let body : String = d["body"] as! String 
     let title : String = d["title"] as! String 
//  print("Title:\("FOSG NOTIFICATION") + body:\(body)") 
     self.showAlertAppDelegate(title: "Federation Of Safety Glass",message:body,buttonTitle:"ok",window:self.window!) 

    } 

    @available(iOS 10.0, *) 
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
     // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background 
     print("Handle push from background or closed\(response.notification.request.content.userInfo)") 
    } 

    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: false, completion: nil) 
    } 
    // Firebase ended here 

} 

et ceci est mon code de fin de serveur php

$tokens = array(); $mess = ''; 
    // queries from db to set the values of variables. 
    function send_notification ($tokens, $message) 
    { 
     $url = 'https://fcm.googleapis.com/fcm/send'; 
     $fields = array(
      'registration_ids' => $tokens, 
      'data' => $message 
      ); 
     $headers = array(
      'Authorization:key = **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); 
     return $result; 
    } 
    $message = array(
     "body" => $mess, 
     "message" => $mess, 
     "title" => "FOSG NOTIFICATION", 
     "sound" => 1, 
     "vibrate" => 1, 
     "badge" => 1, 
    ); 
    $t = implode('',$tokens); 
    if(t != '') $message_status = send_notification($tokens, $message); 

S'il vous plaît me aider à apprendre et résoudre mon problème

+0

Vérifiez cette Quickstart: https://github.com/firebase/quickstart-ios/tree/master/messaging il m'a aidé à mettre en place la messagerie. Ensuite, essayez d'envoyer un message à partir de la console Firebase et assurez-vous que cela fonctionne. Cela aidera à affiner si le problème est avec le code Swift ou le PHP. –

+0

Merci pour votre réponse Jen. Je n'ai pas pu trouver l'erreur en utilisant la source github fournie par vous. Mais la console Firebase envoie les notifications avec succès, c'est seulement quand je les envoie via mon script serveur, que je ne reçois rien. – Sarabjit

+0

La première chose à laquelle je pense est que vous n'avez pas téléchargé le bon certificat sur firebase. Vous pourriez essayer de vérifier cela. –

Répondre

3

Tout a changé les noms de champs avant d'envoyer le json

changez les paramètres suivants:

$fields = array(
      'registration_ids' => $tokens, 
      'data' => $message 
      ); 

à

$fields = array(
      'registration_ids' => $tokens, 
      'notification' => $message, 
      'priority' => 'high' 
      );