Как переключить мой код на UnityWebRequest, чтобы загрузка работала? - PullRequest
0 голосов
/ 05 марта 2020

Приведенный ниже код загружает мой app.apk и устанавливает его, продолжая отслеживать downloadprogress в TextDebug. Я пытаюсь переключиться на UnityWebRequest, но downloadprogress не отображается на TextDebug.

private IEnumerator downLoadFromServer()
{

    string url = "https://example.com/app.apk";


    string savePath = Path.Combine(Application.persistentDataPath, "data");
    savePath = Path.Combine(savePath, "app.apk");

    Dictionary<string, string> header = new Dictionary<string, string>();
    string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
    header.Add("User-Agent", userAgent);
    header["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("test:test"));
    WWW theWWW = new WWW(url, null, header);


    while (!theWWW.isDone)
    {
        //Must yield below/wait for a frame
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Progress: " + theWWW.progress;
        yield return null;
    }

    byte[] yourBytes = theWWW.bytes;

    GameObject.Find("TextDebug").GetComponent<Text>().text = "Done downloading. Size: " + yourBytes.Length;


    //Create Directory if it does not exist
    if (!Directory.Exists(Path.GetDirectoryName(savePath)))
    {
        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Created Dir";
    }

    try
    {
        //Now Save it
        System.IO.File.WriteAllBytes(savePath, yourBytes);
        Debug.Log("Saved Data to: " + savePath.Replace("/", "\\"));
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Saved Data";
    }
    catch (Exception e)
    {
        Debug.LogWarning("Failed To Save Data to: " + savePath.Replace("/", "\\"));
        Debug.LogWarning("Error: " + e.Message);
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Error Saving Data";
    }

    //Install APK
    installApp(savePath);
    }
}

1 Ответ

0 голосов
/ 06 марта 2020

UnityWebRequest.Get и UnityWebRequest.downloadProgress и UnityWebRequest.SetHeader от последнего также примечание

user-agent заголовок автоматически устанавливается Unity, и не рекомендуется устанавливать его на пользовательское значение.

// Better would be to reference this already via the Inspector!
[SerializeField] private Text progressText;

private void Awake ()
{
    // You should avoid Find whenever possible!
    // If you really want/need to use Find at all
    // you really want to do it only ONCE!
    if(! progressText) progressText = GameObject.Find("TextDebug").GetComponent<Text>();
}

private IEnumerator downLoadFromServer()
{  
    var url = "https://example.com/app.apk"; 
    var savePath = Path.Combine(Application.persistentDataPath, "data", "app.apk");              

    using (var uwr = new UnityWebRequest.Get(url))
    {
        uwr.SetHeader("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("test:test")));
        uwr.SendWebRequest();

        while (!uwr.isDone)
        {
            progressText.text = $"Progress: {uwr.downloadProgress:P}";
            yield return null;
        }

        var yourBytes = uwr.downloadHandler.data;

        progressText.text = $"Done downloading. Size: {yourBytes.Length}";

        //Create Directory if it does not exist
        var directoryName = Path.GetDirectoryName(savePath);
        if (!Directory.Exists(directoryName))
        {
             Directory.CreateDirectory(directoryName);
            progressText.text = "Created Dir";
        }

        try
        {
            //Now Save it
            System.IO.File.WriteAllBytes(savePath, yourBytes);
            Debug.Log("Saved Data to: " + savePath.Replace("/", "\\"));
            progressText.text = "Saved Data";
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To Save Data to: " + savePath.Replace("/", "\\"));
            Debug.LogWarning("Error: " + e.Message);
            progressText.text = "Error Saving Data";
        }
    }

    //Install APK
    installApp(savePath);
}

Примечание: напечатано на смартфоне, но я надеюсь, что идея проясняется

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...