/// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="path"></param>
        /// <param name="onSuccess"></param>
        /// <param name="onProgress"></param>
        /// <param name="onFail"></param>
        public Task DownloadLargeFile(string uri, string path, Action onSuccess, Action<float> onProgress, Action onFail, CancellationToken token)
        {
            DownloadHandlerFile fileHandler = null;
            try
            {
                string dir = Path.GetDirectoryName(path);
                FileTools.Instance.CreateDir(dir);
                fileHandler = new DownloadHandlerFile(path);
                fileHandler.removeFileOnAbort = true;
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
            }

            Func<CancellationToken, Task> downloadFunc = async (token) =>
            {
                await Task.Delay(1);
                try
                {
                    UnityWebRequest request = UnityWebRequest.Get(uri);
                    request.downloadHandler = fileHandler;
                    request.SendWebRequest();
                    while (!request.isDone)
                    {
                        await Task.Delay(45);
                        onProgress?.Invoke(request.downloadProgress);
                        if (token.IsCancellationRequested)
                        {
                            request.Abort();
                            break;
                        }
                    }
                    if (request.isDone)
                    {
                        onSuccess?.Invoke();
                    }
                    if (request.result == UnityWebRequest.Result.ProtocolError)
                    {
                        onFail?.Invoke();
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.Message);
                }
            };

            Task task = downloadFunc(token);
            return task;
        }
最后修改日期: 2023年11月23日

作者

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。