Tải file bằng Cloud Storage trên nền tảng Apple

Cloud Storage cho Firebase cho phép bạn tải xuống tệp nhanh chóng và dễ dàng từ nhóm Cloud Storage do Firebase cung cấp và quản lý.

Tạo một tài liệu tham khảo

Để tải xuống tệp, trước tiên hãy tạo tham chiếu Cloud Storage cho tệp bạn muốn tải xuống.

Bạn có thể tạo tham chiếu bằng cách thêm các đường dẫn con vào thư mục gốc của nhóm Cloud Storage hoặc bạn có thể tạo tham chiếu từ URL gs:// hoặc https:// hiện có tham chiếu đến một đối tượng trong Cloud Storage.

Nhanh

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

Mục tiêu-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"];
  

Tải tập tin

Sau khi đã có tài liệu tham khảo, bạn có thể tải file từ Cloud Storage theo ba cách:

  1. Tải xuống NSData trong bộ nhớ
  2. Tải xuống NSURL đại diện cho một tệp trên thiết bị
  3. Tạo một NSURL đại diện cho tệp trực tuyến

Tải xuống trong bộ nhớ

Tải tệp xuống đối tượng NSData trong bộ nhớ bằng phương thức dataWithMaxSize:completion: :. Đây là cách dễ nhất để nhanh chóng tải xuống một tệp nhưng nó phải tải toàn bộ nội dung của tệp vào bộ nhớ. Nếu bạn yêu cầu tệp lớn hơn bộ nhớ khả dụng của ứng dụng, ứng dụng của bạn sẽ gặp sự cố. Để bảo vệ khỏi các vấn đề về bộ nhớ, hãy đảm bảo đặt kích thước tối đa thành kích thước mà bạn biết ứng dụng của mình có thể xử lý hoặc sử dụng phương pháp tải xuống khác.

Nhanh

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

Mục tiêu-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];
  }
}];
    

Tải xuống một tập tin cục bộ

Phương thức writeToFile:completion: tải tệp trực tiếp xuống thiết bị cục bộ. Sử dụng tùy chọn này nếu người dùng của bạn muốn có quyền truy cập vào tệp khi ngoại tuyến hoặc chia sẻ trong một ứng dụng khác. writeToFile:completion: trả về FIRStorageDownloadTask mà bạn có thể sử dụng để quản lý quá trình tải xuống và theo dõi trạng thái tải lên.

Nhanh

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

Mục tiêu-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
  }
}];
    

Nếu muốn chủ động quản lý quá trình tải xuống của mình, bạn có thể sử dụng phương thức writeToFile: và quan sát tác vụ tải xuống thay vì sử dụng trình xử lý hoàn thành. Xem Quản lý tải xuống để biết thêm thông tin.

Tạo URL tải xuống

Nếu bạn đã có cơ sở hạ tầng tải xuống dựa trên URL hoặc chỉ muốn chia sẻ URL, bạn có thể lấy URL tải xuống cho tệp bằng cách gọi phương thức downloadURLWithCompletion: trên tham chiếu Cloud Storage.

Nhanh

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

Mục tiêu-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'
  }
}];
    

Tải xuống hình ảnh với FirebaseUI

FirebaseUI cung cấp các liên kết di động gốc đơn giản, có thể tùy chỉnh và sẵn sàng sản xuất để loại bỏ mã nguyên mẫu và quảng bá các phương pháp hay nhất của Google. Sử dụng FirebaseUI, bạn có thể tải xuống, lưu vào bộ nhớ đệm và hiển thị hình ảnh từ Cloud Storage một cách nhanh chóng và dễ dàng bằng cách sử dụng tính năng tích hợp của chúng tôi với SDWebImage .

Đầu tiên, thêm FirebaseUI vào Podfile của bạn:

pod 'FirebaseStorageUI'

Sau đó, bạn có thể tải hình ảnh trực tiếp từ Cloud Storage vào UIImageView :

Nhanh

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

Mục tiêu-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];
    

Quản lý tải xuống

Ngoài việc bắt đầu tải xuống, bạn có thể tạm dừng, tiếp tục và hủy tải xuống bằng các phương thức pause , resumecancel . Các phương pháp này tăng pause , resumecancel mà bạn có thể quan sát.

Nhanh

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

Mục tiêu-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];
    

Theo dõi tiến trình tải xuống

Bạn có thể đính kèm người quan sát vào FIRStorageDownloadTask để theo dõi tiến trình tải xuống. Việc thêm người quan sát sẽ trả về FIRStorageHandle có thể được sử dụng để xóa người quan sát.

Nhanh

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

Mục tiêu-C

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

Những người quan sát này có thể được đăng ký vào sự kiện FIRStorageTaskStatus :

Sự kiện `FIRStorageTaskStatus` Cách sử dụng điển hình
FIRStorageTaskStatusResume Sự kiện này kích hoạt khi tác vụ bắt đầu hoặc tiếp tục tải xuống và thường được sử dụng cùng với sự kiện FIRStorageTaskStatusPause .
FIRStorageTaskStatusProgress Sự kiện này kích hoạt bất kỳ lúc nào dữ liệu được tải xuống từ Cloud Storage và có thể được dùng để điền vào chỉ báo tiến trình tải xuống.
FIRStorageTaskStatusPause Sự kiện này kích hoạt bất cứ khi nào quá trình tải xuống bị tạm dừng và thường được sử dụng cùng với sự kiện FIRStorageTaskStatusResume .
FIRStorageTaskStatusSuccess Sự kiện này xảy ra khi quá trình tải xuống hoàn tất thành công.
FIRStorageTaskStatusFailure Sự kiện này xảy ra khi quá trình tải xuống không thành công. Kiểm tra lỗi để xác định lý do lỗi.

Khi một sự kiện xảy ra, một đối tượng FIRStorageTaskSnapshot sẽ được truyền trở lại. Ảnh chụp nhanh này là chế độ xem bất biến của nhiệm vụ tại thời điểm sự kiện xảy ra. Đối tượng này chứa các thuộc tính sau:

Tài sản Kiểu Sự miêu tả
progress NSProgress Một đối tượng NSProgress chứa tiến trình tải xuống.
error NSError Đã xảy ra lỗi trong quá trình tải xuống, nếu có.
metadata FIRStorageMetadata nil lượt tải xuống.
task FIRStorageDownloadTask Nhiệm vụ này là ảnh chụp nhanh, có thể được sử dụng để quản lý ( pause , resume , cancel ) nhiệm vụ.
reference FIRStorageReference Các tài liệu tham khảo nhiệm vụ này đến từ.

Bạn cũng có thể xóa người quan sát, riêng lẻ, theo trạng thái hoặc bằng cách xóa tất cả chúng.

Nhanh

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

Mục tiêu-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];
    

Để tránh rò rỉ bộ nhớ, tất cả trình quan sát sẽ bị xóa sau khi FIRStorageTaskStatusSuccess hoặc FIRStorageTaskStatusFailure xảy ra.

Xử lý lỗi

Có một số lý do khiến lỗi có thể xảy ra khi tải xuống, bao gồm cả tệp không tồn tại hoặc người dùng không có quyền truy cập vào tệp mong muốn. Bạn có thể tìm thêm thông tin về lỗi trong phần Xử lý lỗi của tài liệu.

Ví dụ đầy đủ

Một ví dụ đầy đủ về việc tải xuống tệp cục bộ có xử lý lỗi được hiển thị bên dưới:

Nhanh

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

Mục tiêu-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;
    }
  }
}];
    

Bạn cũng có thể lấy và cập nhật siêu dữ liệu cho các tệp được lưu trữ trong Cloud Storage.