بارگیری فایل‌ها با Cloud Storage در پلاتفرم‌های Apple

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

ایجاد مرجع

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

می‌توانید با پیوست کردن مسیرهای فرزند به ریشه Cloud Storage دسته‌بندی خود مرجع ایجاد کنید، یا می‌توانید از 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 که نشان‌دهنده فایل آنلاین است

بارگیری در حافظه

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

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

بارگیری در فایل محلی

روش 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
  }
}];
    

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

تولید نشانی وب بارگیری

اگر ازقبل زیرساخت بارگیری براساس نشانی‌های وب دارید، یا فقط می‌خواهید نشانی وبی برای هم‌رسانی داشته باشید، می‌توانید با فراخوانی روش 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 پیوندهای بومی تلفن همراه ساده، قابل‌سفارشی‌سازی، و آماده تولید ارائه می‌دهد تا کد کلیشه‌ای را حذف کند و روال‌های مطلوب 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 ذخیره شده‌اند.