ดาวน์โหลดไฟล์ด้วย Cloud Storage บนแพลตฟอร์ม Apple

Cloud Storage สำหรับ Firebase ช่วยให้คุณดาวน์โหลดไฟล์จากที่เก็บ ข้อมูล Cloud Storage ที่ Firebase จัดเตรียมและจัดการโดย Firebase ได้อย่างรวดเร็วและง่ายดาย

สร้างข้อมูลอ้างอิง

หากต้องการดาวน์โหลดไฟล์ ขั้นแรก ให้สร้างการอ้างอิง Cloud Storage ไปยังไฟล์ที่คุณต้องการดาวน์โหลด

คุณสามารถสร้างข้อมูลอ้างอิงได้โดยเพิ่มเส้นทางลูกต่อท้ายรากของที่เก็บข้อมูล Cloud Storage ของคุณ หรือคุณสามารถสร้างข้อมูลอ้างอิงจาก gs:// หรือ https:// URL ที่มีอยู่ซึ่งอ้างอิงออบเจ็กต์ใน 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")

วัตถุประสงค์-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 ได้ 3 วิธี:

  1. ดาวน์โหลดไปยัง NSData ในหน่วยความจำ
  2. ดาวน์โหลดไปยัง NSURL ที่แสดงไฟล์บนอุปกรณ์
  3. สร้าง NSURL ที่แสดงไฟล์ออนไลน์

ดาวน์โหลดในหน่วยความจำ

ดาวน์โหลดไฟล์ไปยังวัตถุ NSData ในหน่วยความจำโดยใช้เมธอด dataWithMaxSize:completion: นี่เป็นวิธีที่ง่ายที่สุดในการดาวน์โหลดไฟล์อย่างรวดเร็ว แต่จะต้องโหลดเนื้อหาทั้งหมดของไฟล์ของคุณลงในหน่วยความจำ หากคุณขอไฟล์ที่มีขนาดใหญ่กว่าหน่วยความจำที่มีอยู่ของแอป แอปของคุณจะขัดข้อง เพื่อป้องกันปัญหาด้านหน่วยความจำ ตรวจสอบให้แน่ใจว่าได้ตั้งค่าขนาดสูงสุดเป็นสิ่งที่คุณรู้ว่าแอปของคุณสามารถจัดการได้ หรือใช้วิธีการดาวน์โหลดอื่น

สวิฟท์

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

วัตถุประสงค์-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 ซึ่งคุณสามารถใช้จัดการการดาวน์โหลดและตรวจสอบสถานะของการอัปโหลด

สวิฟท์

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

วัตถุประสงค์-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

สวิฟท์

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

วัตถุประสงค์-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 :

สวิฟท์

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

วัตถุประสงค์-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 เหตุการณ์ที่คุณสามารถสังเกตได้

สวิฟท์

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

วัตถุประสงค์-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 ที่สามารถใช้เพื่อลบผู้สังเกตการณ์ได้

สวิฟท์

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

วัตถุประสงค์-C

// Add a progress observer to a download task
FIRStorageHandle 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 การอ้างอิงงานนี้มาจาก

คุณยังสามารถลบผู้สังเกตการณ์ออกทีละคน ตามสถานะ หรือโดยลบทั้งหมดก็ได้

สวิฟท์

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

วัตถุประสงค์-C

// Create a task listener handle
FIRStorageHandle 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
  }
}
    

วัตถุประสงค์-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 ได้ด้วย