// Base function to made a request. private IEnumerator GetRequest(string uri, System.Action<BackendRequestResult> responseCallback) { BackendRequestResult result = new BackendRequestResult(); using (UnityWebRequest webRequest = UnityWebRequest.Get(uri)) { // Request and wait for the desired page. yield return webRequest.SendWebRequest(); if (!webRequest.isNetworkError && webRequest.responseCode == 200) { string responseStr = System.Text.Encoding.UTF8.GetString(webRequest.downloadHandler.data); result.Success = true; result.ResponseString = responseStr; result.ResponseBytes = webRequest.downloadHandler.data; if (responseCallback != null) { responseCallback(result); } } else { result.Success = false; result.ResponseString = ""; result.ErrorString = "GetRequest -> Something went wrong while doing a Get Request"; if (responseCallback != null) { responseCallback(result); } } } }
// Download a file directly to the folder streaming assets. public void DownloadFile(string uri, System.Action<BackendRequestResult,string> resultCallback = null) { var lastSlash = uri.LastIndexOf('/'); if(lastSlash==-1) { BackendRequestResult result = new BackendRequestResult(); result.ErrorString = "Invalid input uri string"; result.Success = false; if (resultCallback != null) { resultCallback(result, ""); } } string filePath = Application.streamingAssetsPath + uri.Substring(lastSlash); StartCoroutine(GetRequest(uri, (BackendRequestResult result) => { if (result.Success) { try { // Ensure Download Folder Path exists Directory.CreateDirectory(Application.streamingAssetsPath); // Write file to disk using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { fs.Write(result.ResponseBytes, 0, result.ResponseBytes.Length); } } catch (Exception ex) { result.ErrorString = "Backend request succeeded of but the system were unable to write the file to disk. Reason: "+ ex.Message; result.Success = false; } } if (resultCallback != null) { resultCallback(result, filePath); } })); }