iOS中的推送通知使用Firebase和PHP

问题描述:

我对开发非常陌生,无法在此主题上找到很多端到端的支持。我尽我所能地使用了Firebase帮助页面。 我无法接收我的ios设备上的通知,但FCM在android上完美运行。 这是在XcodeiOS中的推送通知使用Firebase和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 

} 

我的appdelegate,这是从服务器端我的代码在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); 

请帮助我学习和解决我的问题

+0

看看这个快速入门:https://github.com/firebase/quickstart-ios/tree/master/messaging它帮助我建立的消息。然后尝试从Firebase控制台发送消息并确保可行。如果问题出在Swift代码或PHP上,这将有助于缩小范围。 –

+0

谢谢你的回复仁。 我找不到使用您提供的github源的错误。 但Firebase控制台正在成功发送通知,只有当我通过我的服务器脚本发送它们时,我才收到任何内容。 – Sarabjit

+0

我能想到的第一件事就是您没有将正确的证书上传到Firebase。你可以尝试双重检查。 –

发送前刚换的字段名json

更改以下内容:

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

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