首页 > 解决方案 > 如何将我的代码切换到 UnityWebRequest 以便下载进度有效?

问题描述

下面的代码下载我的并安装它,app.apk同时继续跟踪downloadprogress. TextDebug我正在尝试切换到UnityWebRequestdownloadprogress没有显示在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);
    }
}

标签: c#unity3d

解决方案


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);
}

注意:在智能手机上输入,但我希望这个想法很清楚


推荐阅读