הורדת קבצים באמצעות Cloud Storage ל-Unity

בדף הזה מוסבר איך משתמשים ב-SDK של Cloud Storage for Firebase כדי להוריד קבצים מקטגוריה של Cloud Storage.

יצירת קובץ עזר

כדי להוריד קובץ, קודם צריך ליצור הפניה ב-Cloud Storage לקובץ שרוצים להוריד.

אפשר ליצור הפניה על ידי הוספת נתיבי צאצא לשורש של קטגוריית Cloud Storage, או ליצור הפניה מכתובת URL קיימת של 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. הורדה מכתובת URL
  2. הורדה למערך בייטים
  3. הורדה באמצעות סטרימינג
  4. הורדה לקובץ מקומי

השיטה שבה תשתמשו כדי לאחזר את הקבצים תלויה באופן שבו אתם רוצים לצרוך את הנתונים במשחק.

הורדה מכתובת URL

אם אתם רוצים להשתמש בכתובת URL עם WWW או UnityWebRequest של Unity, אתם יכולים לקבל כתובת URL להורדה של קובץ על ידי קריאה ל-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 processing) שלכם כארגומנט הראשון. הנציג הזה יופעל בשרשור ברקע עם 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() מקבלת ארגומנט אופציונלי אחרי מעבד עיבוד זרמי נתונים (stream processing), שמאפשר לבטל את הפעולה או לקבל התראה על ההתקדמות.

הורדה לקובץ מקומי

השיטה 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> משלכם כקריאה חוזרת (callback) לסימוני ההתקדמות.

// 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.