دانلود فایل ها با Cloud Storage در پلتفرم های اپل

Cloud Storage for Firebase به شما امکان می‌دهد تا به سرعت و به راحتی فایل‌ها را از یک مخزن Cloud Storage که توسط فایربیس ارائه و مدیریت می‌شود، دانلود کنید.

ایجاد یک مرجع

برای دانلود یک فایل، ابتدا یک مرجع Cloud Storage برای فایلی که می‌خواهید دانلود کنید ایجاد کنید .

شما می‌توانید با اضافه کردن مسیرهای فرزند به ریشه‌ی مخزن Cloud Storage خود، یک مرجع ایجاد کنید، یا می‌توانید از یک آدرس اینترنتی gs:// یا https:// موجود که به یک شیء در Cloud Storage ارجاع می‌دهد، یک مرجع ایجاد کنید.

سویفت

// 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")

هدف-سی

// 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 ایجاد کنید که فایل را به صورت آنلاین نمایش دهد

دانلود در حافظه

با استفاده از متد dataWithMaxSize:completion: فایل را در یک شیء NSData در حافظه دانلود کنید. این ساده‌ترین راه برای دانلود سریع یک فایل است، اما باید کل محتوای فایل شما را در حافظه بارگذاری کند. اگر فایلی بزرگتر از حافظه موجود برنامه خود درخواست کنید، برنامه شما از کار می‌افتد. برای محافظت در برابر مشکلات حافظه، مطمئن شوید که حداکثر اندازه را روی چیزی تنظیم کرده‌اید که می‌دانید برنامه شما می‌تواند از پس آن برآید، یا از روش دانلود دیگری استفاده کنید.

سویفت

// 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!)
  }
}
    

هدف-سی

// 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];
  }
}];
    

دانلود در یک فایل محلی

متد writeToFile:completion: یک فایل را مستقیماً در یک دستگاه محلی دانلود می‌کند. اگر کاربران شما می‌خواهند در حالت آفلاین به فایل دسترسی داشته باشند یا آن را در یک برنامه دیگر به اشتراک بگذارند، از این متد استفاده کنید. writeToFile:completion: یک FIRStorageDownloadTask را برمی‌گرداند که می‌توانید از آن برای مدیریت دانلود و نظارت بر وضعیت آپلود استفاده کنید.

سویفت

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

هدف-سی

// 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
  }
}];
    

اگر می‌خواهید دانلود خود را به طور فعال مدیریت کنید، می‌توانید از متد writeToFile: استفاده کنید و به جای استفاده از completion handler، فرآیند دانلود را مشاهده کنید. برای اطلاعات بیشتر به بخش مدیریت دانلودها مراجعه کنید.

ایجاد آدرس اینترنتی دانلود

اگر از قبل زیرساخت دانلود مبتنی بر URLها را دارید، یا فقط می‌خواهید یک URL برای اشتراک‌گذاری داشته باشید، می‌توانید با فراخوانی متد downloadURLWithCompletion: در یک مرجع Cloud Storage URL دانلود یک فایل را دریافت کنید.

سویفت

// 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'
  }
}
    

هدف-سی

// 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 اتصالات بومی موبایل ساده، قابل تنظیم و آماده برای تولید را فراهم می‌کند تا کدهای تکراری را حذف کرده و بهترین شیوه‌های گوگل را ترویج دهد. با استفاده از FirebaseUI می‌توانید با استفاده از ادغام ما با SDWebImage، تصاویر را به سرعت و به راحتی از Cloud Storage دانلود، ذخیره و نمایش دهید.

ابتدا، FirebaseUI را به Podfile خود اضافه کنید:

pod 'FirebaseStorageUI'

سپس می‌توانید تصاویر را مستقیماً از Cloud Storage در یک UIImageView بارگذاری کنید:

سویفت

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

هدف-سی

// 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 را ایجاد می‌کنند که می‌توانید مشاهده کنید.

سویفت

// 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()
    

هدف-سی

// 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 برمی‌گرداند که می‌توان از آن برای حذف ناظر استفاده کرد.

سویفت

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

هدف-سی

// 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 برگردانده می‌شود. این snapshot یک نمای تغییرناپذیر از وظیفه، در زمان وقوع رویداد است. این شیء شامل ویژگی‌های زیر است:

ملک نوع توضیحات
progress NSProgress یک شیء NSProgress که شامل پیشرفت دانلود است.
error NSError خطایی که هنگام دانلود رخ داده است، در صورت وجود.
metadata FIRStorageMetadata دانلودها nil است.
task FIRStorageDownloadTask این یک تصویر لحظه‌ای از وظیفه است که می‌تواند برای مدیریت ( pause ، resume ، cancel ) وظیفه استفاده شود.
reference FIRStorageReference مرجعی که این وظیفه از آن آمده است.

همچنین می‌توانید ناظران را به صورت جداگانه، بر اساس وضعیت یا با حذف همه آنها حذف کنید.

سویفت

// 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()
    

هدف-سی

// 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 حذف می‌شوند.

مدیریت خطاها

دلایل مختلفی برای بروز خطا در هنگام دانلود وجود دارد، از جمله وجود نداشتن فایل یا عدم دسترسی کاربر به فایل مورد نظر. اطلاعات بیشتر در مورد خطاها را می‌توانید در بخش «مدیریت خطاها» در مستندات بیابید.

مثال کامل

یک مثال کامل از دانلود به یک فایل محلی با مدیریت خطا در زیر نشان داده شده است:

سویفت

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

هدف-سی

// 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 ذخیره شده‌اند را دریافت و به‌روزرسانی کنید .