OStack程序员社区-中国程序员成长平台

标题: php - 使用 iOS 和 PHP 发送 fcm 推送通知 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:08
标题: php - 使用 iOS 和 PHP 发送 fcm 推送通知

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

我在服务器端的代码:

<?php
    function send_notification ($tokens, $message)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        $fields = array(
             'registration_ids' => $tokens,
             'data' => $message
            );
        $headers = array(
            'Authorization:key = AIzaSyDjrLKZGs4OcIgBPxpFnTzGeZHur4v9V8U',
            '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;
    }

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

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

    mysqli_close($conn);
    $message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
    $message_status = send_notification($tokens, $message);
    echo $message_status;
?>

Swift 中的代码:

UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Override point for customization after application launch.
        Util.copyFile(fileName: "db.zanjanwireFinal01.db")

        //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("DCS: " + 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("DCS: " + token)
                RegisterUsers(testStr: token)
            }
        }

        func RegisterUsers(testStr:String){

            let request = NSMutableURLRequest(url: NSURL(string:
            request.httpMethod = "OST"
            var dataString = "Token=\(testStr)"
            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("fffffffffatemeeeeeee")
                    print("error=\(error)")
                    return
                }
                print("response = \(response)")

                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("responseString = \(responseString)")
            }
            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) -> Void) {

            UIApplication.shared.applicationIconBadgeNumber += 1

            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "com.DouglasDevlops.BadgeWasUpdated"), object: nil)
        }



Best Answer-推荐答案


像这样构建您的通知负载,

enter image description here

关于php - 使用 iOS 和 PHP 发送 fcm 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50230279/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4