菜鸟教程小白 发表于 2022-12-11 20:08:25

php - 使用 iOS 和 PHP 发送 fcm 推送通知


                                            <p><p>我正在尝试编写一个应用程序来通过 Firebase Cloud Messaging 接收通知。它最初在我尝试通过 Firebase 控制台发送消息时起作用,但是当我尝试使用 PHP Web 服务做同样的事情时,作为响应,它显示成功,但我既没有收到消息,也无法获得更多通知通过 Firebase 控制台。我该如何解决这个问题?</p>

<p>我在服务器端的代码:</p>

<pre><code>&lt;?php
    function send_notification ($tokens, $message)
    {
      $url = &#39;https://fcm.googleapis.com/fcm/send&#39;;
      $fields = array(
             &#39;registration_ids&#39; =&gt; $tokens,
             &#39;data&#39; =&gt; $message
            );
      $headers = array(
            &#39;Authorization:key = AIzaSyDjrLKZGs4OcIgBPxpFnTzGeZHur4v9V8U&#39;,
            &#39;Content-Type: application/json&#39;
            );
      $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(&#39;Curl failed: &#39; . curl_error($ch));
      }
      curl_close($ch);
      return $result;
    }

    $conn = mysqli_connect(&#34;localhost:3306&#34;, &#34;minaaaa&#34;, &#34;tt@2018&#34;, &#34;dbSurvey&#34;);

    $sql = &#34;Select Token From users&#34;;
    $result = mysqli_query($conn,$sql);
    $tokens = array();
    if(mysqli_num_rows($result) &gt; 0 ){
      while ($row = mysqli_fetch_assoc($result)) {
            $tokens[] = $row[&#34;Token&#34;];
      }
    }

    mysqli_close($conn);
    $message = array(&#34;message&#34; =&gt; &#34; FCM PUSH NOTIFICATION TEST MESSAGE&#34;);
    $message_status = send_notification($tokens, $message);
    echo $message_status;
?&gt;
</code></pre>

<p>Swift 中的代码:</p>

<pre><code>UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: ?) -&gt; Bool {

      // Override point for customization after application launch.
      Util.copyFile(fileName: &#34;db.zanjanwireFinal01.db&#34;)

      //let alert = UIAlertController(title: title, message: message , preferredStyle: .alert)
      UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]){(isGranted, err)
            in
            if err != nil {
            }
            else
            {
                UNUserNotificationCenter.current().delegate = self
                Messaging.messaging().delegate = self
                if let token = InstanceID.instanceID().token() {
                  print(&#34;DCS: &#34; + token)
                  self.RegisterUsers(testStr: token)
                }
                DispatchQueue.main.async {
                  UIApplication.shared.registerForRemoteNotifications()
                }
            }
      }

      FirebaseApp.configure()

            return true
      }

      func ConnectToFCM() {
            Messaging.messaging().shouldEstablishDirectChannel = true

            if let token = InstanceID.instanceID().token() {
                print(&#34;DCS: &#34; + token)
                RegisterUsers(testStr: token)
            }
      }

      func RegisterUsers(testStr:String){

            let request = NSMutableURLRequest(url: NSURL(string:
            request.httpMethod = &#34;POST&#34;
            var dataString = &#34;Token=\(testStr)&#34;
            print (dataString)
            request.httpBody = dataString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in

                if error != nil {
                  print(&#34;fffffffffatemeeeeeee&#34;)
                  print(&#34;error=\(error)&#34;)
                  return
                }
                print(&#34;response = \(response)&#34;)

                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print(&#34;responseString = \(responseString)&#34;)
            }
            task.resume()
      }

      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.
            //FirstMenueViewController().update()
            Messaging.messaging().shouldEstablishDirectChannel = false
      }

      func applicationWillEnterForeground(_ application: UIApplication) {
            FirstMenueViewController().update()
            // 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.
            ConnectToFCM()
      }

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

      func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
            ConnectToFCM()
      }

      func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {

            UIApplication.shared.applicationIconBadgeNumber += 1

            NotificationCenter.default.post(name: NSNotification.Name(rawValue: &#34;com.DouglasDevlops.BadgeWasUpdated&#34;), object: nil)
      }
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>像这样构建您的通知负载,</p>

<p> <a href="/image/4EuFu.jpg" rel="noreferrer noopener nofollow"><img src="/image/4EuFu.jpg" alt="enter image description here"/></a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于php - 使用 iOS 和 PHP 发送 fcm 推送通知,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/50230279/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/50230279/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: php - 使用 iOS 和 PHP 发送 fcm 推送通知