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

标签 php ios apple-push-notifications

我正在尝试编写一个应用程序以通过 Firebase 云消息传递接收通知。它最初在我尝试通过 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 = "POST"
            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)
        }

最佳答案

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

enter image description here

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

相关文章:

ios - 在 iOS 中旋转 View 时如何计算仿射平移参数?

ios - React-native包管理器问题

ios - Ionic - OneSignal 不适用于 iOS 13.x

php - 从已知位置查找最近的列出(数组?)城市

php - 为什么 MySQL 不返回最后插入的 id,它返回 0?

javascript - jQuery Ajax 脚本相互淘汰

php - 无法向 apns 发送消息?

php - 在instr()和IN中使用数组的SQLIte语句

ios - 如何在 swift 中定义 HEX 颜色宏

ios - 以编程方式生成 APNS 证书