הורדת קבצים באמצעות Cloud Storage בפלטפורמות של Apple

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

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

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

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

Swift

// Create a reference with an initial file path and name
let pathReference = storage.reference(withPath: "images/stars.jpg")

// Create a reference from a Google Cloud Storage URI
let gsReference = storage.reference(forURL: "gs://<your-firebase-storage-bucket>/images/stars.jpg")

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

Objective-C

// Create a reference with an initial file path and name
FIRStorageReference *pathReference = [storage referenceWithPath:@"images/stars.jpg"];

// Create a reference from a Google Cloud Storage URI
FIRStorageReference *gsReference = [storage referenceForURL:@"gs://<your-firebase-storage-bucket>/images/stars.jpg"];

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
FIRStorageReference *httpsReference = [storage referenceForURL:@"https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg"];
  

הורדת קבצים

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

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

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

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

Swift

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)
  }
}
    

Objective-C

// Create a reference to the file you want to download
FIRStorageReference *islandRef = [storageRef child:@"images/island.jpg"];

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
[islandRef dataWithMaxSize:1 * 1024 * 1024 completion:^(NSData *data, NSError *error){
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    UIImage *islandImage = [UIImage imageWithData:data];
  }
}];
    

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

ה-method‏ writeToFile:completion: מורידה קובץ ישירות למכשיר מקומי. השתמשו בזה אם המשתמשים שלכם רוצים לקבל גישה לקובץ במצב אופליין או לשתף אותו באפליקציה אחרת. writeToFile:completion: מחזיר FIRStorageDownloadTask שבו אתם יכולים להשתמש כדי לנהל את ההורדה ולעקוב אחרי סטטוס ההעלאה.

Swift

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Create local filesystem URL
let localURL = URL(string: "path/to/image")!

// Download to the local filesystem
let downloadTask = islandRef.write(toFile: localURL) { url, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Local file URL for "images/island.jpg" is returned
  }
}
    

Objective-C

// Create a reference to the file you want to download
FIRStorageReference *islandRef = [storageRef child:@"images/island.jpg"];

// Create local filesystem URL
NSURL *localURL = [NSURL URLWithString:@"path/to/image"];

// Download to the local filesystem
FIRStorageDownloadTask *downloadTask = [islandRef writeToFile:localURL completion:^(NSURL *URL, NSError *error){
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Local file URL for "images/island.jpg" is returned
  }
}];
    

אם אתם רוצים לנהל באופן פעיל את ההורדה, אתם יכולים להשתמש ב-method‏ writeToFile: ולצפות במשימת ההורדה, במקום להשתמש ב-completion handler. מידע נוסף זמין במאמר ניהול הורדות.

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

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

Swift

// Create a reference to the file you want to download
let starsRef = storageRef.child("images/stars.jpg")

// Fetch the download URL
starsRef.downloadURL { url, error in
  if let error = error {
    // Handle any errors
  } else {
    // Get the download URL for 'images/stars.jpg'
  }
}
    

Objective-C

// Create a reference to the file you want to download
FIRStorageReference *starsRef = [storageRef child:@"images/stars.jpg"];

// Fetch the download URL
[starsRef downloadURLWithCompletion:^(NSURL *URL, NSError *error){
  if (error != nil) {
    // Handle any errors
  } else {
    // Get the download URL for 'images/stars.jpg'
  }
}];
    

הורדת תמונות באמצעות FirebaseUI

‫FirebaseUI מספק קישורים פשוטים, ניתנים להתאמה אישית ומוכנים לייצור לניידים, כדי למנוע קוד שחוזר על עצמו (boilerplate) ולקדם את השיטות המומלצות של Google. באמצעות FirebaseUI אפשר להוריד, לשמור במטמון ולהציג תמונות מ-Cloud Storage במהירות ובקלות, באמצעות השילוב שלנו עם SDWebImage.

קודם כול, מוסיפים את FirebaseUI לקובץ Podfile:

pod 'FirebaseStorageUI'

אחרי זה תוכלו לטעון תמונות ישירות מ-Cloud Storage אל UIImageView:

Swift

// Reference to an image file in Firebase Storage
let reference = storageRef.child("images/stars.jpg")

// UIImageView in your ViewController
let imageView: UIImageView = self.imageView

// Placeholder image
let placeholderImage = UIImage(named: "placeholder.jpg")

// Load the image using SDWebImage
imageView.sd_setImage(with: reference, placeholderImage: placeholderImage)
    

Objective-C

// Reference to an image file in Firebase Storage
FIRStorageReference *reference = [storageRef child:@"images/stars.jpg"];

// UIImageView in your ViewController
UIImageView *imageView = self.imageView;

// Placeholder image
UIImage *placeholderImage;

// Load the image using SDWebImage
[imageView sd_setImageWithStorageReference:reference placeholderImage:placeholderImage];
    

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

בנוסף להתחלת הורדות, אפשר להשהות, להמשיך ולבטל הורדות באמצעות השיטות pause,‏ resume ו-cancel. השיטות האלה מפעילות את האירועים pause,‏ resume ו-cancel, שאפשר לצפות בהם.

Swift

// Start downloading a file
let downloadTask = storageRef.child("images/mountains.jpg").write(toFile: localFile)

// Pause the download
downloadTask.pause()

// Resume the download
downloadTask.resume()

// Cancel the download
downloadTask.cancel()
    

Objective-C

// Start downloading a file
FIRStorageDownloadTask *downloadTask = [[storageRef child:@"images/mountains.jpg"] writeToFile:localFile];

// Pause the download
[downloadTask pause];

// Resume the download
[downloadTask resume];

// Cancel the download
[downloadTask cancel];
    

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

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

Swift

// Add a progress observer to a download task
let observer = downloadTask.observe(.progress) { snapshot in
  // A progress event occurred
}
    

Objective-C

// Add a progress observer to a download task
NSString *observer = [downloadTask observeStatus:FIRStorageTaskStatusProgress
                                         handler:^(FIRStorageTaskSnapshot *snapshot) {
  // A progress event occurred
}];
    

אפשר לרשום את הצופים האלה לאירוע FIRStorageTaskStatus:

אירוע `FIRStorageTaskStatus` שימוש אופייני
FIRStorageTaskStatusResume האירוע הזה מופעל כשהמשימה מתחילה או ממשיכה להוריד, ולעיתים קרובות משתמשים בו בשילוב עם האירוע FIRStorageTaskStatusPause.
FIRStorageTaskStatusProgress האירוע הזה מופעל בכל פעם שמתבצעת הורדה של נתונים מ-Cloud Storage, ואפשר להשתמש בו כדי לאכלס אינדיקטור של התקדמות ההורדה.
FIRStorageTaskStatusPause האירוע הזה מופעל בכל פעם שההורדה מושהית, ולעיתים קרובות משתמשים בו בשילוב עם האירוע FIRStorageTaskStatusResume.
FIRStorageTaskStatusSuccess האירוע הזה מופעל כשההורדה מסתיימת בהצלחה.
FIRStorageTaskStatusFailure האירוע הזה מופעל כשהורדה נכשלת. בודקים את השגיאה כדי להבין מה הסיבה לכישלון.

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

נכס סוג תיאור
progress NSProgress אובייקט NSProgress שמכיל את התקדמות ההורדה.
error NSError שגיאה שאירעה במהלך ההורדה, אם הייתה כזו.
metadata FIRStorageMetadata nil בהורדות.
task FIRStorageDownloadTask המשימה שתמונת המצב הזו שייכת לה, שאפשר להשתמש בה כדי לנהל (pause, resume, cancel) את המשימה.
reference FIRStorageReference המקור שממנו הגיעה המשימה.

אפשר גם להסיר צופים – בנפרד, לפי סטטוס או את כולם.

Swift

// Create a task listener handle
let observer = downloadTask.observe(.progress) { snapshot in
// A progress event occurred
}

// Remove an individual observer
downloadTask.removeObserver(withHandle: observer)

// Remove all observers of a particular status
downloadTask.removeAllObservers(for: .progress)

// Remove all observers
downloadTask.removeAllObservers()
    

Objective-C

// Create a task listener handle
NSString *observer = [downloadTask observeStatus:FIRStorageTaskStatusProgress
                                         handler:^(FIRStorageTaskSnapshot *snapshot) {
  // A progress event occurred
}];

// Remove an individual observer
[downloadTask removeObserverWithHandle:observer];

// Remove all observers of a particular status
[downloadTask removeAllObserversForStatus:FIRStorageTaskStatusProgress];

// Remove all observers
[downloadTask removeAllObservers];
    

כדי למנוע דליפות זיכרון, כל הצופים מוסרים אחרי שמתרחש אירוע FIRStorageTaskStatusSuccess או FIRStorageTaskStatusFailure.

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

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

דוגמה מלאה

דוגמה מלאה להורדה לקובץ מקומי עם טיפול בשגיאות:

Swift

// Create a reference to the file we want to download
let starsRef = storageRef.child("images/stars.jpg")

// Start the download (in this case writing to a file)
let downloadTask = storageRef.write(toFile: localURL)

// Observe changes in status
downloadTask.observe(.resume) { snapshot in
  // Download resumed, also fires when the download starts
}

downloadTask.observe(.pause) { snapshot in
  // Download paused
}

downloadTask.observe(.progress) { snapshot in
  // Download reported progress
  let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
    / Double(snapshot.progress!.totalUnitCount)
}

downloadTask.observe(.success) { snapshot in
  // Download completed successfully
}

// Errors only occur in the "Failure" case
downloadTask.observe(.failure) { snapshot in
  guard let errorCode = (snapshot.error as? NSError)?.code else {
    return
  }
  guard let error = StorageErrorCode(rawValue: errorCode) else {
    return
  }
  switch (error) {
  case .objectNotFound:
    // File doesn't exist
    break
  case .unauthorized:
    // User doesn't have permission to access file
    break
  case .cancelled:
    // User cancelled the download
    break

  /* ... */

  case .unknown:
    // Unknown error occurred, inspect the server response
    break
  default:
    // Another error occurred. This is a good place to retry the download.
    break
  }
}
    

Objective-C

// Create a reference to the file we want to download
FIRStorageReference *starsRef = [storageRef child:@"images/stars.jpg"];

// Start the download (in this case writing to a file)
FIRStorageDownloadTask *downloadTask = [storageRef writeToFile:localURL];

// Observe changes in status
[downloadTask observeStatus:FIRStorageTaskStatusResume handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Download resumed, also fires when the download starts
}];

[downloadTask observeStatus:FIRStorageTaskStatusPause handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Download paused
}];

[downloadTask observeStatus:FIRStorageTaskStatusProgress handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Download reported progress
  double percentComplete = 100.0 * (snapshot.progress.completedUnitCount) / (snapshot.progress.totalUnitCount);
}];

[downloadTask observeStatus:FIRStorageTaskStatusSuccess handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Download completed successfully
}];

// Errors only occur in the "Failure" case
[downloadTask observeStatus:FIRStorageTaskStatusFailure handler:^(FIRStorageTaskSnapshot *snapshot) {
  if (snapshot.error != nil) {
    switch (snapshot.error.code) {
      case FIRStorageErrorCodeObjectNotFound:
        // File doesn't exist
        break;

      case FIRStorageErrorCodeUnauthorized:
        // User doesn't have permission to access file
        break;

      case FIRStorageErrorCodeCancelled:
        // User canceled the upload
        break;

      /* ... */

      case FIRStorageErrorCodeUnknown:
        // Unknown error occurred, inspect the server response
        break;
    }
  }
}];
    

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