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

‫Cloud Storage for Firebase מאפשר לכם להוריד קבצים במהירות ובקלות מקטגוריית Cloud Storage שמסופקת ומנוהלת על ידי Firebase.

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

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

אפשר ליצור קובץ עזר על ידי הוספת נתיבי צאצא לשורש של קטגוריית Cloud Storage, או ליצור קובץ עזר מכתובת URL קיימת של gs:// או https:// שמפנה לאובייקט ב-Cloud Storage.

// Create a reference with an initial file path and name
StorageReference path_reference = storage->GetReference("images/stars.jpg");

// Create a reference from a Cloud Storage URI
StorageReference gs_reference = storage->GetReferenceFromUrl("gs://bucket/images/stars.jpg");

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
StorageReference https_reference = storage->GetReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

הורדת קבצים

אחרי שיש לכם הפניה, אתם יכולים להוריד קבצים מ-Cloud Storage בשלוש דרכים:

  1. הורדה למאגר נתונים זמני בזיכרון
  2. הורדה לנתיב ספציפי במכשיר
  3. יוצרים כתובת URL של מחרוזת שמייצגת את הקובץ באינטרנט.

הורדה לזיכרון

מורידים את הקובץ למאגר בייטים בזיכרון באמצעות השיטה GetBytes(). זו הדרך הקלה ביותר להוריד קובץ במהירות, אבל היא מחייבת טעינה של כל תוכן הקובץ לזיכרון. אם תבקשו קובץ שגדול מהזיכרון הפנוי של האפליקציה, היא תקרוס. כדי למנוע בעיות בזיכרון, חשוב להגדיר את הגודל המקסימלי לגודל שהאפליקציה יכולה להתמודד איתו, או להשתמש בשיטת הורדה אחרת.

// Create a reference to the file you want to download
StorageReference island_ref = storage_ref.Child("images/island.jpg");

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
const size_t kMaxAllowedSize = 1 * 1024 * 1024
int8_t byte_buffer[kMaxAllowedSize];
firebase::Future<size_t> future = island_ref.GetBytes(byte_buffer, kMaxAllowedSize);

בשלב הזה הבקשה נשלחה, אבל אנחנו צריכים להמתין עד שה-Future יסתיים כדי שנוכל לקרוא את הקובץ. בדרך כלל משחקים פועלים בלולאה, והם פחות מבוססים על קריאות חוזרות (callbacks) מאשר אפליקציות אחרות, לכן בדרך כלל תצטרכו לבצע סקר כדי לבדוק אם הפעולה הושלמה.

// In the game loop that polls for the result...

if (future.status() != firebase::kFutureStatusPending) {
  if (future.status() != firebase::kFutureStatusComplete) {
    LogMessage("ERROR: GetBytes() returned an invalid future.");
    // Handle the error...
  } else if (future.Error() != firebase::storage::kErrorNone) {
    LogMessage("ERROR: GetBytes() returned error %d: %s", future.Error(),
               future.error_message());
    // Handle the error...
  } else {
    // byte_buffer is now populated with data for "images/island.jpg"
  }
}

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

השיטה GetFile() מורידה קובץ ישירות למכשיר מקומי. האפשרות הזו מתאימה אם המשתמשים רוצים לגשת לקובץ במצב אופליין או לשתף אותו באפליקציה אחרת.

// Create a reference to the file you want to download
StorageReference islandRef = storage_ref.Child("images/island.jpg"];

// Create local filesystem URL
const char* local_url = "file:///local/images/island.jpg";

// Download to the local filesystem
Future<size_t> future = islandRef.GetFile(local_url);

// Wait for Future to complete...

if (future.Error() != firebase::storage::kErrorNone) {
  // Uh-oh, an error occurred!
} else {
  // The file has been downloaded to local file URL "images/island.jpg"
}

הפונקציה GetFile() מקבלת ארגומנט אופציונלי של Controller שבו אפשר להשתמש כדי לנהל את ההורדה. מידע נוסף זמין במאמר בנושא ניהול הורדות.

יצירת כתובת URL להורדה

אם כבר יש לכם תשתית הורדה שמבוססת על כתובות URL, או שאתם רק רוצים כתובת URL לשיתוף, אתם יכולים לקבל את כתובת ה-URL להורדה של קובץ על ידי קריאה ל-method‏ GetDownloadUrl() בהפניה של Cloud Storage.

// Create a reference to the file you want to download
StorageReference stars_ref = storage_ref.Child("images/stars.jpg");

// Fetch the download URL
firebase::Future<std::string> future = stars_ref.GetDownloadUrl();

// Wait for Future to complete...

if (future.Error() != firebase::storage::kErrorNone) {
  // Uh-oh, an error occurred!
} else {
  // Get the download URL for 'images/stars.jpg'
  std::string download_url = future.Result();
}

ניהול ההורדות

בנוסף להפעלת הורדות, אפשר להשהות, להמשיך ולבטל הורדות באמצעות השיטות Pause(),‏ Resume() ו-Cancel() ב-Controller, שאפשר להעביר לשיטות GetBytes() או GetFile().

// Start downloading a file
Controller controller;
storage_ref.Child("images/mountains.jpg").GetFile(local_file, nullptr, &controller);

// Pause the download
controller.Pause();

// Resume the download
controller.Resume();

// Cancel the download
controller.Cancel();

מעקב אחרי התקדמות ההורדה

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

class MyListener : public firebase::storage::Listener {
 public:
  virtual void OnProgress(firebase::storage::Controller* controller) {
    // A progress event occurred
  }
};

{
  // Start uploading a file
  MyEventListener my_listener;
  storage_ref.Child("images/mountains.jpg").GetFile(local_file, my_listener);
}

טיפול בשגיאות

יכולות להיות כמה סיבות לשגיאות בהורדה, למשל: הקובץ לא קיים או שלמשתמש אין הרשאה לגשת לקובץ הרצוי. מידע נוסף על שגיאות זמין בקטע טיפול בשגיאות במסמכי התיעוד.

השלבים הבאים

אפשר גם לקבל ולעדכן מטא-נתונים של קבצים שמאוחסנים ב-Cloud Storage.