使用 Unity 適用的 Cloud Storage 下載檔案

Cloud Storage for Firebase 可讓您輕鬆快速地從 Firebase 提供及管理的 Cloud Storage bucket 下載檔案。

可建立參照

如要下載檔案,請先建立要下載檔案的 Cloud Storage 參照。

如要建立參照,請將子路徑附加至 Cloud Storage bucket 的根目錄,或從現有的 gs:// 或 https:// 網址建立參照,指向 Cloud Storage 中的物件。

// 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 的 WWW 或 UnityWebRequest,可以呼叫 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(),並將自己的串流處理器做為第一個引數傳遞。這個委派代表會在背景執行緒上呼叫,並提供 Stream,讓您執行需要大量延遲時間的作業或計算,例如將內容儲存至磁碟。

// 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中儲存檔案的中繼資料。