【发布时间】:2022-01-24 11:07:34
【问题描述】:
在对调用 firebase 存储提出一些建议后,主要是如何(从同步 POV)我应该检查文件是否存在。
要使用下面的 DownloadCoroutine 函数将我在状态文件中读取的上下文设置为 json 并将其传递给 JsonTextReader,只要文件首先存在(作为新用户它将不是)。
然后我编写了下面的 checkIfFile exists 函数,它也可以独立运行(获取 URL 以证明该文件确实存在)。一旦这个函数完成,我就会设置一个布尔值(SaveFileExists)来表示这是/不是一个现有文件,然后根据状态创建一个。
我的问题在于这些函数的执行顺序,我需要在执行任何其他方法之前进行检查,目前它们都在 LoadScene 函数中调用。我认为我需要做的是使检查返回任务的异步方法?如果是这样,它的外观和我应该从哪里调用它,我已经尝试过了,但我认为它会一直锁定主线程。
所以现在的状态是因为那个 bool 没有及时改变,所以存储文件的下载没有发生并且 Json 永远不会被读入并抛出错误,在控制台输出的末尾输出了 checkfile URL ,任何帮助都会很棒,谢谢。
private IEnumerator DownloadCoroutine(string path)
{
var storage = FirebaseStorage.DefaultInstance;
var storageReference = storage.GetReference(path);
if (SaveFileExists == true)
{
var DownloadTask = storageReference.GetBytesAsync(long.MaxValue);
yield return new WaitUntil(predicate: () => DownloadTask.IsCompleted);
byte[] fileContents = DownloadTask.Result;
retrievedSaveFile = Encoding.Default.GetString(fileContents);
Debug.Log("Downloading the save file");
}
else
{
createNewSaveFile(path);
}
}
检查Json文件是否存在
private void CheckIfFileExists(string path)
{
var storage = FirebaseStorage.DefaultInstance;
var storageReference = storage.GetReference(path);
storageReference.GetDownloadUrlAsync().ContinueWith(task => {
if (!task.IsFaulted && !task.IsCanceled) {
Debug.Log("Download URL: " + task.Result);
SaveFileExists = true;
}
else{
Debug.Log("file doesnt exist so we create one");
}
});
}
加载场景
public IEnumerator LoadLastScene()
{
var User = FirebaseAuth.DefaultInstance.CurrentUser;
Debug.Log("USERID IS " + User.UserId.ToString());
CheckIfFileExists("Saves://" + User.UserId.ToString() + "saveFile.json");
yield return DownloadCoroutine("Saves://" + User.UserId.ToString() +
"saveFile.json");
}
【问题讨论】:
标签: c# firebase unity3d asynchronous firebase-storage