使用 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 的 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!");
    }
});

透過串流下載

使用 Stream 下載檔案時,您可以在載入資料的同時處理資料。 這樣您在處理下載內容時,就能享有最大的彈性。呼叫 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 中的檔案中繼資料。