使用 Flutter + OneSignal 为 PlayerID 发送推送通知

Send Push notification with Flutter + OneSignal for PlayerID

我正在创建一个日历式推送系统。我需要在为用户创建时间表时系统只向他发送通知,我创建了系统来管理此 PHP,有人知道如何帮助我吗?

我远不是移动应用方面的专家,所以有人应该更正/确认这一点。

要在您的应用程序中完成推送通知,您可以使用 'live' 连接(例如 websocket)或者您可以使用轮询。

我对 websockets 了解不多,我认为 CakePHP 不可能做到这一点(不确定)。编辑:绝对不可能开箱即用,但存在插件。

当您使用轮询时,您会每隔一段时间重复一次 GET 请求(每小时一次,每分钟一次,视需要而定)并检查是否有新信息。
例如,您的 CakePHP 页面可能是一个采用 lastUpdated 参数的操作,其中 returns 自该时间戳以来的新信息。然后,应用程序每 x 分钟请求一次此页面,每次都设置 lastUpdated 参数。当有新信息时,响应不为空,应用可以处理。

这确实意味着该应用需要始终 运行 在后台运行,并且请求的数量可能会变得相当大(取决于轮询间隔)。

如果您使用的是 OneSignal。您可以使用 Playerid 发送到那个单独的设备,但是您必须在服务器端存储 playerid,以便您知道要发送到哪个设备。我个人在初始状态下这样做,并对我的 api 执行 http.post 以将播放器 ID 保存到我的数据库中,供该特定用户使用。

您当然可以通过使用 OneSignal 的标签来实现相同的目的(如果同一个人在一台设备上有多个帐户,则很有用)。

要发送通知,请在 php 中使用 curl。

<?php
function sendMessage(){
    $content = array(
        "en" => 'English Message'
        );

    $fields = array(
        'app_id' => "your-app-id",
        'include_player_ids' => array("playerid-you-want-to-send-to"),
        'data' => array("foo" => "bar"),
        'contents' => $content
    );

    $fields = json_encode($fields);
    print("\nJSON sent:\n");
    print($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);

print("\n\nJSON received:\n");
print($return);
print("\n");
?>

在 Flutter 中,获取包,导入它并:

void oneSignal() {
OneSignal.shared.init("app-id");

OneSignal.shared.setNotificationReceivedHandler((OSNotification notification) 

   {
     //do what you need to do with upcoming notification, get title for example
     print(notification.payload.title);
   }
}