Hello guys, I’m developing a project where I want to receive information from an API using UnityEngine.Networking.UnityWebRequest, following the documentation.
The following code works normally when there is internet connectivity, but it never returns any information when offline. Does anyone have any idea what could be happening?
Here is my code:
public static IEnumerator GetCurrentTime(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
GameData.NetworkState = NetworkStates.Null;
Debug.Log("Connecting");
yield return webRequest.SendWebRequest();
switch (webRequest.result)
{
case UnityWebRequest.Result.Success:
WorldTime api = JsonUtility.FromJson<WorldTime>(webRequest.downloadHandler.text);
GameData.DateTimeNow = DateTime.Parse(api.dateTime);
GameData.NetworkState = NetworkStates.Online;
Debug.Log("API get successful.");
break;
default:
Debug.LogError("API get an error: " + webRequest.error);
GameData.NetworkState = NetworkStates.Offline;
break;
}
}
}
If you can help me with another question, I use this code to identify if the device is connected to the internet.
Is there any better way to check connectivity than calling an API?
Thank you all for your help.