Example #1
0
 // Ask the client if the user can delete his score
 private void SendDeleteRequest(PlayerRequestData data)
 {
     // If the client agrees, the callback OnDataReceived is called
     client.PostRequest(client.deleteUrl, data, result => {
         OnDataReceived(result);
     });
 }
 public void OnSendClicked(System.Action <PlayerRequestData> callback)
 {
     // If inputs are valid, a new PlayerRequestData entry is created, and lastPlayerSent is filled in CustomLeaderboard
     if (InputsAreValid())
     {
         var player = new PlayerRequestData(userIdField.text, float.Parse(userScoreField.text, CultureInfo.InvariantCulture));
         leaderBoard.GetComponent <CustomLeaderboard>().lastPlayerSent = userIdField.text;
         callback(player);
     }
     else
     {
         Debug.LogWarning("Invalid Input");
     }
 }
    public IEnumerator Post(string url, PlayerRequestData data, System.Action <string> callback)
    {
        var jsonData = JsonUtility.ToJson(data);

        Debug.Log(jsonData);

        // Check if the urls are matching
        using (UnityWebRequest www = UnityWebRequest.Post(url, jsonData))
        {
            www.SetRequestHeader("content-type", "application/json");
            www.uploadHandler.contentType = "application/json";
            www.uploadHandler             = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(jsonData));

            // Send the web request
            yield return(www.SendWebRequest());

            if (www.isNetworkError)
            {
                Debug.Log(www.error);
            }
            else
            {
                // If everything went well :
                if (www.isDone)
                {
                    // Handle the result
                    var result = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);

                    //Format into json to be able to work with JsonUtil
                    result = "{\"result\":" + result + "}";

                    // Execute the callback function after everything is done, with the Json result as parameter
                    callback(result);
                }
                else
                {
                    //Handle the error (Even though I'm only "printing" error, this prevents the function from going sideways if the www request encountered a problem)
                    Debug.Log("Error! Couldn't post data.");
                }
            }
        }
    }
 // PostRequest is called from the CustomLeaderboard script, and in turn calls the Post Coroutine
 // This method is used to either create, delete or update a player
 public void PostRequest(string url, PlayerRequestData data, System.Action <string> callback)
 {
     StartCoroutine(Post(url, data, callback));
 }