> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 推播通知快速入門

> 透過 Game Manager 或 SetupPushNotification Admin API 搭配 Amazon SNS 路由，設定 iOS APNS 和 Android GCM 通道的 PlayFab 推播通知。

PlayFab 的推播通知是透過連結三個主要系統來啟用的：

1. 玩家的裝置作業系統 (Android、iOS 等)
2. 廠商專屬通道 (Google、Apple 等)
3. 跨平台訊息路由 (透過 Amazon Simple Notification Service (SNS) 的 PlayFab)。

<Note>
  如果其中任何系統未連結，用戶端將停止接收通知。意外變更三個系統中的其中一個並導致連結中斷相當容易。此外，在流程中的任何單一點，都很難得知所有系統是否已正確設定。
</Note>

## PlayFab 推播路由系統

每個 PlayFab 遊戲在指定時間可以啟用一個 Google (GCM) 和一個 Apple 推播 (APNS、APNS\_SANDBOX) 通知通道。這些可以透過下列兩種方式之一進行設定：

1. 使用 **Game Manager** 中 **Settings -> Push Notifications** 下的 UI。
2. 使用 **PlayFab Admin API** - [SetupPushNotification](xref:titleid.playfabapi.com.admin.title-widedatamanagement.setuppushnotification)。

如需更詳細的設定資訊，請閱讀這些教學課程：

* [Android 推播通知](/zh-TW/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-android)
* [iOS 推播通知](/zh-TW/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-ios)

## 遊戲內推播訊息

推播訊息會因開發引擎/平台而異。不過，接收推播通知最簡單的方式，是在 Android 上使用搭配我們 SDK 和 Firebase 雲端通訊 (FCM) 外掛程式的 Unity 專案，或在 iOS 上只使用 Unity。

* **在 Android 上接收推播** - 這需要外掛程式。支援最完善的外掛程式是原生 FCM 外掛程式。
* **在 iOS 上接收推播** - 基本推播訊息*不*需要外掛程式。

<Tip>
  如需如何設定 [FCM Unity 外掛程式](https://firebase.google.com/docs/cloud-messaging/unity/client)或在 [Android Studio](https://firebase.google.com/docs/cloud-messaging/android/client) 上設定推播的指示，請參閱 FCM 文件。
</Tip>

## 測試設定

設定遊戲和用戶端後，您可以使用 PlayFab 伺服器 API [SendPushNotification](xref:titleid.playfabapi.com.server.accountmanagement.sendpushnotification) 測試您的設定。此 API 可讓您視需要傳送任意數量的推播通知，且不需額外付費。

您可以使用 PlayFab CloudScript 服務作為快速且安全的伺服器 API 環境。從那裡，可以視需要傳送推播通知。

若要使用此方法測試您的設定，請將下列範例中的程式碼上傳或附加至您遊戲的 CloudScript。

### 範例

請考慮下列情境：

* 您遊戲中的玩家可以存取以排名統計資料為基礎的排行榜。

* 每位玩家可以支付 1 CH 貨幣，挑戰與目前玩家相距最多 5 個名次的另一位玩家。

首先，請考慮如下列範例螢幕擷取畫面所示的虛擬貨幣 (如需如何定義虛擬貨幣的相關資訊，請參閱[貨幣](/zh-TW/services/playfab/economy-monetization/economy-v2/tutorials/currencies)教學課程)。

<img src="https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-new-currency.png?fit=max&auto=format&n=3hg2JQs0m7qmDqay&q=85&s=529f8a8499e64af54013e73f64e933fd" alt="PlayFab Economy - 貨幣 - 新貨幣" width="1800" height="969" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-new-currency.png" />

現在，請考慮為每位玩家定義的下列統計資料 (如需如何產生測試排行榜的相關資訊，請參閱[存取已封存的錦標賽結果](/zh-TW/services/playfab/community/leaderboards/tournaments-leaderboards/accessing-archived-tournament-results)教學課程)。

<img src="https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-statistics-player-rank.png?fit=max&auto=format&n=3hg2JQs0m7qmDqay&q=85&s=dfd2bdb1c0160f95676fd7fbf69781af" alt="PlayFab 玩家統計資料 - 排名" width="1026" height="456" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-statistics-player-rank.png" />

設定好這些必要條件後，您就可以設定推播通知挑戰系統。

下列用戶端程式碼會呼叫 CloudScript `ChallengePlayer`。

```csharp theme={null}
public void ChallengeRandomClosePlayer(string currentPlayerId) {
    PlayFabClientAPI.GetLeaderboardAroundPlayer(new GetLeaderboardAroundPlayerRequest() {
        MaxResultsCount = 10,
        StatisticName = "Rank",
        PlayFabId = currentPlayerId,
    }, result => OnLeaderboardLoaded(result,currentPlayerId),OnPlayFabError);
}

private void OnLeaderboardLoaded(GetLeaderboardAroundPlayerResult leaderboard, string currentPlayerId) {
    var index = (int)(UnityEngine.Random.value * (leaderboard.Leaderboard.Count-1));
    if (leaderboard.Leaderboard[index].PlayFabId == currentPlayerId)
        index = (index + 1) % leaderboard.Leaderboard.Count;
    var targetId = leaderboard.Leaderboard[index].PlayFabId;

    PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest() {
        FunctionName = "ChallengePlayer",
        FunctionParameter = new Dictionary<string, object>() {
            { "TargetId", targetId }
        }
    }, null, OnPlayFabError);
}

public void OnPlayFabError(PlayFabError obj) {
    Debug.Log(obj.GenerateErrorReport());
}
```

`ChallengePlayer` CloudScript 程式碼會處理要求、驗證排行榜狀態，並將挑戰推播通知傳送給目標。

```javascript theme={null}
handlers.ChallengePlayer = function (args) {
    var targetId = args.TargetId;
    var leaderboard = server.GetLeaderboardAroundUser({
        MaxResultsCount : 10,
        PlayFabId : currentPlayerId,
        StatisticName : "Rank"
    });

    for(var i = 0; i < leaderboard.Leaderboard.length; i++) {
        var target = leaderboard.Leaderboard[i];
        if(target.PlayFabId !== targetId) continue;

        // subtract virtual currency from current player
        server.SubtractUserVirtualCurrency({
            VirtualCurrency : "CH",
            PlayFabId : currentPlayerId,
            Amount : 1
        });

        // get current player profile
        var profile = server.GetPlayerProfile({
            PlayFabId : currentPlayerId
        }).PlayerProfile;

        // try to send push notification
        try {
            server.SendPushNotification({
                Recipient : targetId,
                Package : {
                    Message : `${profile.DisplayName} challenges you for a battle!`,
                    Title: "You have been challenged",
                }
            });
        } catch (ex) {
            // Target player has not registered for Push Notifications
        }
        return;
    }
}
```

## 推播通知的使用

能夠使用推播通知是一項很棒的能力。然而，如果*濫用*，可能會導致使用者選擇不再接收未來的通知，甚至*完全離開遊戲*。

不過，如果審慎使用，推播通知可以是建立和維護遊戲社群的最佳工具之一。

推播通知是一種*射後不理*的訊息協定，不保證一定會送達。

<Note>
  請記住，*無法保證*您的玩家會收到、開啟或參與您的訊息。考量到這一點，最好將訊息作為*額外*功能使用，而不是作為遊戲迴圈的關鍵部分。
</Note>

在 iOS 平台上，作業系統會給予應用程式一次性的對話方塊提示，讓使用者決定推播通知的狀態。使用者做出初始選擇後，此設定會一直保持，直到：

* 應用程式更新或重新安裝。

* 使用者從手機的設定功能表變更設定。

對於 Android 應用程式，通知預設為啟用，並可隨時從用戶端開啟和關閉。

<Tip>
  最好在每個工作階段都重新初始化您的通知接聽程式。
</Tip>

## 資源

下列資源提供有關本快速入門中主題的其他資訊：

* [Firebase Unity SDK](https://firebase.google.com/docs/unity/setup)：適用於 Unity 的一體化 FCM 解決方案。在所有其他功能中，此 SDK 可讓您接收和處理透過 FCM 傳送的推播通知。
* [Push It Real Good: How to Get Players to Say Yes to Push Notifications](https://blog.playfab.com/blog/push-it-real-good-how-get-players-say-yes-push-notifications/)：這篇部落格文章詳細說明使用推播通知的其他策略和技巧。
* [推播通知](https://blog.playfab.com/blog/push-sep-17)：這篇部落格文章說明推播功能的最新升級，以及改用 FCM 作為 Android 的主要外掛程式。
* [Postman 快速入門](/zh-TW/services/playfab/sdks/postman/postman-quickstart)：本快速入門說明如何使用 Postman 測試我們的 API。


## Related topics

- [Android 推播通知](/zh-TW/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-android.md)
- [iOS 推播通知](/zh-TW/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-ios.md)
- [PFPlatformSpecificRegisterForIOSPushNotificationRequest](/zh-TW/services/playfab/api-references/c/pfplatformspecifictypes/structs/pfplatformspecificregisterforiospushnotificationrequest.md)
- [推播通知範本](/zh-TW/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notification-templates.md)
- [服務 C API 概觀 - PFPlatformSpecificTypes.h](/zh-TW/services/playfab/api-references/c/pfplatformspecifictypes/pfplatformspecifictypes_members.md)
