通过 Unity 版 Cloud Storage 下载文件

Cloud Storage for Firebase 可让您快速轻松地从 Firebase 提供和管理的 Cloud Storage 存储桶中下载文件。

创建引用

如需下载某个文件,请先为要下载的文件创建一个 Cloud Storage 引用

您可以通过将子路径附加到 Cloud Storage 存储桶的根目录来创建引用,也可以根据指向 Cloud Storage 中对象的现有 gs://https:// 网址创建引用。

// Create a reference with an initial file path and name StorageReference pathReference =  storage.GetReference("images/stars.jpg"); // Create a reference from a Google Cloud Storage URI StorageReference gsReference =  storage.GetReferenceFromUrl("gs://bucket/images/stars.jpg"); // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! StorageReference httpsReference =  storage.GetReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

下载文件

有了引用之后,您可以通过四种方法从 Cloud Storage 中下载文件:

  1. 通过网址下载
  2. 下载到字节数组
  3. 使用流下载
  4. 下载至本地文件

您用于检索文件的方法取决于您将如何在游戏中使用数据。

通过网址下载

如果您希望将一个网址与 Unity 的 WWWUnityWebRequest 配合使用,可以通过调用 GetDownloadUrlAsync() 来获取文件的下载网址。

// Fetch the download URL reference.GetDownloadUrlAsync().ContinueWithOnMainThread(task => {  if (!task.IsFaulted && !task.IsCanceled) {  Debug.Log("Download URL: " + task.Result);  // ... now download the file via WWW or UnityWebRequest.  } });

下载到字节数组

您可以使用 GetBytesAsync() 方法将文件下载到内存中的字节缓冲区。这种方法会将文件的全部内容加载到内存中。 如果您请求下载的文件大于应用的可用内存,您的应用将崩溃。 为了防止出现内存问题,请务必将大小上限设置为已知您的应用可以处理的数值,或使用其他下载方法。

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes) const long maxAllowedSize = 1 * 1024 * 1024; reference.GetBytesAsync(maxAllowedSize).ContinueWithOnMainThread(task => {  if (task.IsFaulted || task.IsCanceled) {  Debug.LogException(task.Exception);  // Uh-oh, an error occurred!  }  else {  byte[] fileContents = task.Result;  Debug.Log("Finished downloading!");  } });

通过流下载

使用流下载文件可以让您在加载数据的过程中即对其进行处理, 从而最大限度提高您在处理下载时的灵活性。调用 GetStreamAsync() 并传递您自己的流处理器作为第一个参数。此代理将被一个流在后台线程中调用,因而您可以执行容易出现延迟的操作或计算,例如将内容存储至磁盘。

// Download via a Stream reference.GetStreamAsync(stream => {  // Do something with the stream here.  //  // This code runs on a background thread which reduces the impact  // to your framerate.  //  // If you want to do something on the main thread, you can do that in the  // progress eventhandler (second argument) or ContinueWith to execute it  // at task completion. }, null, CancellationToken.None);

GetStreamAsync() 在流处理器后面会使用一个可选参数,该参数允许您取消操作或接收进度通知。

下载至本地文件

GetFileAsync() 方法可将文件直接下载至本地设备。如果您的用户希望在离线时也可以访问该文件,或者希望在其他应用中共享该文件,则可使用此方法。

// Create local filesystem URL string localUrl = "file:///local/images/island.jpg"; // Download to the local filesystem reference.GetFileAsync(localUrl).ContinueWithOnMainThread(task => {  if (!task.IsFaulted && !task.IsCanceled) {  Debug.Log("File downloaded.");  } });

您可以将监听器附加到下载进程中,以便监控下载进程的进度。监听器采用标准 System.IProgress<T> 接口。您可以使用 StorageProgress 类的一个实例,提供自己的 Action<T> 作为进度完成的回调。

// Create local filesystem URL string localUrl = "file:///local/images/island.jpg"; // Start downloading a file Task task = reference.GetFileAsync(localFile,  new StorageProgress<DownloadState>(state => {  // called periodically during the download  Debug.Log(String.Format(  "Progress: {0} of {1} bytes transferred.",  state.BytesTransferred,  state.TotalByteCount  ));  }), CancellationToken.None); task.ContinueWithOnMainThread(resultTask => {  if (!resultTask.IsFaulted && !resultTask.IsCanceled) {  Debug.Log("Download finished.");  } });

处理错误

导致下载出错的原因有很多,包括文件不存在,或者用户不具备访问相应文件的权限。如需详细了解这些错误,请参阅文档的处理错误部分。

后续步骤

对于存储在 Cloud Storage 中的文件,您还可以获取和更新元数据