使用 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 的檔案取得及更新中繼資料