2
\$\begingroup\$

This is a class I built to handle post/get requests to URL's, but also check for connection and provide different callbacks depending on success or failure. It is intended to work without being attached to a GameObject by using static methods.

It can set up like so:

MHSOnline.Domain = "http://yourdomain.com";
MHSOnline.DirectoryPath = "data/myapp";
MHSOnline.PingFile = "ping.php";

And used like so:

MHSOnline.Get("request.php?type=highscores", success => {
    // Success
}, failure => {
    // Failure
});

And the .Post method can be passed a Dictionary of post parameters. I use MonoBehaviourEmpty as a component to attach to GameObjects created at runtime to handle coroutines. Also... the ping file is just a file online that contains the string "true", if anything is returned other than true it assumes something is wrong and returns false on the NetworkAvailable check.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace MugHeadStudios
{
/// <summary>
/// MonoBehaviourEmpty is a dummy class added to run coroutines on temporary GameObjects
/// </summary>
public class MonoBehaviourEmpty : MonoBehaviour {}

/// <summary>
/// MHS online.
/// </summary>
public class MHSOnline
{
    // PROPERTIES

    static public string Domain;
    static public string DirectoryPath;
    static public string PingFile;

    public delegate void WWWCallBack(string RequestedString = "");
    public delegate void WWWErrorCallBack(string RequestedString = "");

    // PUBLIC

    /// <summary>
    /// Post request to the specified URL with Data, optional CallBack and ErrorCallBack.
    /// </summary>
    /// <param name="File">File.</param>
    /// <param name="Data">Data.</param>
    /// <param name="CallBack">Call back.</param>
    /// <param name="ErrorCallBack">Error call back.</param>
    static public void Post(string URL, Dictionary<string, string> Data, WWWCallBack CallBack = null, WWWErrorCallBack ErrorCallBack = null)
    {
        MHSOnline.NetworkAvailable(success => {
            if(CallBack != null)
            {
                GameObject newGameObject = new GameObject("Co-routine (POST)");
                newGameObject.AddComponent<MonoBehaviourEmpty>().StartCoroutine(MHSOnline.IRequest(URL, Data, CallBack, newGameObject));
            }
        }, fail => {
            if(ErrorCallBack != null)
                ErrorCallBack(fail);
        });
    }

    /// <summary>
    /// Get request to the specified URL, optional CallBack and ErrorCallBack.
    /// </summary>
    /// <param name="File">File.</param>
    /// <param name="CallBack">Call back.</param>
    /// <param name="ErrorCallBack">Error call back.</param>
    static public void Get(string URL, WWWCallBack CallBack = null, WWWErrorCallBack ErrorCallBack = null)
    {
        MHSOnline.NetworkAvailable(success => {
            if(CallBack != null)
            {
                GameObject newGameObject = new GameObject("Co-routine (GET)");
                newGameObject.AddComponent<MonoBehaviourEmpty>().StartCoroutine(MHSOnline.IRequest(URL, null, CallBack, newGameObject));
            }
        }, fail => {
            if(ErrorCallBack != null)
                ErrorCallBack(fail);
        });
    }

    /// <summary>
    /// Calls back success or failue
    /// </summary>
    /// <param name="SuccessCallBack">Success call back.</param>
    /// <param name="ErrorCallBack">Error call back.</param>
    static public void NetworkAvailable(WWWCallBack SuccessCallBack = null, WWWErrorCallBack ErrorCallBack = null)
    {
        NetworkReachability networkReachability = Application.internetReachability;

        if(networkReachability == NetworkReachability.NotReachable)
            ErrorCallBack("NetworkReachability.NotReachable");

        GameObject newGameObject = new GameObject("Co-routine (Network)");
        newGameObject.AddComponent<MonoBehaviourEmpty>().StartCoroutine(MHSOnline.INetworkAvailable(success => {
            SuccessCallBack();
        }, fail => {
            ErrorCallBack(fail);
        }, newGameObject));
    }

    // PRIVATE

    static private IEnumerator INetworkAvailable(WWWCallBack SuccessCallBack = null, WWWErrorCallBack ErrorCallBack = null, GameObject TempObject = null)
    {
        WWW www = new WWW(MHSOnline.Domain+"/"+MHSOnline.DirectoryPath+"/"+MHSOnline.PingFile);

        yield return www;

        if(www.text == "true")
            SuccessCallBack();
        else
            ErrorCallBack(www.error);

        if(TempObject != null)
            MonoBehaviour.Destroy(TempObject);
    }

    static private IEnumerator IRequest(string File, Dictionary<string, string> Data = null, WWWCallBack CallBack = null, GameObject TempObject = null)
    {
        WWW www;

        if(Data != null)
        {
            WWWForm form = new WWWForm();

            foreach(KeyValuePair<string, string> KV in Data)
                form.AddField(KV.Key, KV.Value);

            www = new WWW(MHSOnline.Domain+"/"+MHSOnline.DirectoryPath+"/"+File, form);
        }
        else
        {
            www = new WWW(MHSOnline.Domain+"/"+MHSOnline.DirectoryPath+"/"+File);
        }

        if(www != null)
            yield return www;

        if(CallBack != null)
        {
            string result = www.text;
            CallBack(result);

            if(TempObject != null)
                MonoBehaviour.Destroy(TempObject);
        }
    }
}   
}
\$\endgroup\$
  • \$\begingroup\$ And what is your question? \$\endgroup\$ – Patrick Mevzek May 1 '18 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.