تنزيل الملفات باستخدام 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];
  }
}];
    

تنزيل الملف إلى ملف محلي

تنزّل طريقة 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:الطريقة ومراقبة مهمة التنزيل بدلاً من استخدام معالج الإكمال. اطّلِع على إدارة التنزيلات للحصول على مزيد من المعلومات.

إنشاء عنوان URL للتنزيل

إذا كان لديك بنية أساسية للتنزيل تستند إلى عناوين URL، أو إذا كنت تريد الحصول على عنوان URL لمشاركته، يمكنك الحصول على عنوان URL للتنزيل لملف من خلال استدعاء الطريقة 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];
    

مراقبة مستوى تقدُّم عملية التنزيل

يمكنك إرفاق مراقبين بـ FIRStorageDownloadTasks من أجل تتبُّع مستوى تقدُّم عملية التنزيل. تؤدي إضافة مراقب إلى عرض 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.