php - Swift:未收到 FCM 通知

标签 php swift firebase push-notification firebase-notifications

我使用 FCM 进行通知。

在 firebase 控制台中,我可以发送通知,但通过 PHP 代码未收到且无法自定义它

PHP 代码:

$data['TITLE'] = $title;
$data['TEXT'] = $text;

$fcmFields = array('to'=>$to,
                   'data'=>$data,
                   'priority'=>'high',
                   'time_to_live'=>$time);

$headers = array('Authorization: key='.API_ACCESS_KEY,'Content-Type: application/json');

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fcmFields));
$result = curl_exec($ch);
curl_close($ch);
return $result;

注意:通过这个 php 代码我可以发送通知 Android 设备

Swift 代码:

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

        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        return true
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
    }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print(userInfo)

        completionHandler([])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print(userInfo)

        completionHandler()
    }
}

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }
}

1-我可以通过 Google 控制台发送通知并收到通知,但不会在我的应用日志中打印任何内容

2-我可以通过 php 代码向 Android 设备发送通知,但无法向 ios 设备发送通知

3- didReceiveRemoteNotification 完全不起作用

你能帮我吗?

最佳答案

我在 PHP 代码中添加了“通知”并修复了

$fcmFields = array('to'=>$to,
                   'data'=>$data,
                   'notification'=>array('title'=>'x','body'=>'y'),
                   'priority'=>'high',
                   'time_to_live'=>$time);

关于php - Swift:未收到 FCM 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156291/

相关文章:

php - Symfony 2.1 REST API 登录无处不在

ios - 可以编辑滑动以删除(在 UITableView 中)默认文本或翻译它吗?

ios - Firebase 连接管理器应该只返回一个结果

php - 没有管理员权限的XAMPP服务

php - 如何使用 PHP 获取选定日期的星期几?

php - 使用 PHP 从 Microsoft Graph API 获取访问 token

ios - 将视频合成为带有过渡的单个电影

ios - 使用 Array 中的 pathExtension 作为 TableViewCell 图像源

swift - 如何查询 Firebase 数据库中的嵌套数据?

ios - 通过修改 emailVerified 属性进行 Firebase 无密码身份验证?