I am creating application in unity 2021.3.22f1 (for android and IOS mobiles). I am searching for any options to implement the speed test in the app. I have a hard time finding any paid or free services that let me do api calls from c# to get the speed test details like upload / download. I also tried downloading a hosted file and using stopwatch to calculate the time taken from start to completion and thereby calculating the speed.
I used a file URL to make a web request. the started stopwatch when download progress started and keep checking time taken with amount of data downloaded. This was not giving correct values. Then I tried calculating speed at regular intervals (approximately every 5%) and took the max value ever registered from 0 to 100% download. This seems to have given better values but is still not giving exactly what speed test websites give. part of code I used is given below. I am new to implementing speed test in a mobile application. Any suggestions regarding paid/free API or based on the file download logic below or any other solutions is much appreciated. Also I don't want any option that requires opening a webpage within my application. Thanks in advance
_request = UnityWebRequest.Get("www.example.com/file1"); //here i used athe file url
_request.downloadHandler = new DownloadHandlerBuffer();
Stopwatch stopwatch;
InitialCallback?.Invoke(_request);
_request.SendWebRequest();
UnityEngine.Debug.Log("Web request started");
while (_request.downloadProgress == 0)
{
yield return null;
}
stopwatch = Stopwatch.StartNew();
UnityEngine.Debug.Log("Download Started");
while (_request.downloadProgress < 1)
{
yield return null;
float currentProgress = _request.downloadProgress;
if (currentProgress >= prevProgress + 0.05f || currentProgress >= 1)
{
byte[] dataTemp = _request.downloadHandler.data;
int currData = dataTemp.Length - prevData;
long curTime = stopwatch.ElapsedMilliseconds - prevTime;
float dataInMegaBitsTemp = (currData * 8) / (1000 * 1000);
float downloadSpeedTemp = (dataInMegaBitsTemp / ((float)curTime / 1000f));
if (averageSpeed < downloadSpeedTemp)
{
averageSpeed = downloadSpeedTemp;
}
prevData = dataTemp.Length;
prevTime = stopwatch.ElapsedMilliseconds;
prevProgress = currentProgress;
}
}
stopwatch.Stop();
UnityEngine.Debug.Log("Download Stopped");
if (_request.result != UnityWebRequest.Result.Success)
{
FailureCallback?.Invoke($"Download failed. \n error: " + _request.error);
yield break;
}
UnityEngine.Debug.Log("Speed : " + averageSpeed);