Pobieraj pliki za pomocą Cloud Storage na platformach Apple

Cloud Storage dla Firebase umożliwia szybkie i łatwe pobieranie plików z zasobnika Cloud Storage udostępnianego i zarządzanego przez Firebase.

Utwórz odniesienie

Aby pobrać plik, najpierw utwórz odniesienie do Cloud Storage dla pliku, który chcesz pobrać.

Możesz utworzyć odniesienie, dołączając ścieżki podrzędne do katalogu głównego zasobnika Cloud Storage lub możesz utworzyć odniesienie z istniejącego adresu URL gs:// lub https:// odnoszącego się do obiektu w Cloud Storage.

Szybki

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

Cel 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"];
  

Pobierz pliki

Po uzyskaniu referencji możesz pobierać pliki z Cloud Storage na trzy sposoby:

  1. Pobierz do NSData w pamięci
  2. Pobierz do NSURL reprezentującego plik na urządzeniu
  3. Wygeneruj NSURL reprezentujący plik online

Pobierz w pamięci

Pobierz plik do obiektu NSData w pamięci przy użyciu metody dataWithMaxSize:completion: Jest to najłatwiejszy sposób szybkiego pobrania pliku, ale wymaga załadowania całej zawartości pliku do pamięci. Jeśli poprosisz o plik większy niż dostępna pamięć aplikacji, aplikacja ulegnie awarii. Aby zabezpieczyć się przed problemami z pamięcią, ustaw maksymalny rozmiar na taki, jaki obsługuje Twoja aplikacja, lub użyj innej metody pobierania.

Szybki

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

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

Pobierz do pliku lokalnego

Metoda writeToFile:completion: pobiera plik bezpośrednio na urządzenie lokalne. Użyj tej opcji, jeśli użytkownicy chcą mieć dostęp do pliku w trybie offline lub udostępnić go w innej aplikacji. writeToFile:completion: zwraca FIRStorageDownloadTask , którego możesz użyć do zarządzania pobieraniem i monitorowania statusu wysyłania.

Szybki

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

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

Jeśli chcesz aktywnie zarządzać pobieraniem, możesz użyć metody writeToFile: i obserwować zadanie pobierania, zamiast korzystać z procedury obsługi zakończenia. Aby uzyskać więcej informacji, zobacz Zarządzanie pobieraniem .

Wygeneruj adres URL pobierania

Jeśli masz już infrastrukturę pobierania opartą na adresach URL lub po prostu chcesz udostępnić adres URL, możesz uzyskać adres URL pobierania pliku, wywołując metodę downloadURLWithCompletion: w odwołaniu do Cloud Storage.

Szybki

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

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

Pobieranie obrazów za pomocą FirebaseUI

FirebaseUI zapewnia proste, konfigurowalne i gotowe do produkcji natywne powiązania mobilne, które pozwalają wyeliminować szablonowy kod i promować najlepsze praktyki Google. Korzystając z FirebaseUI, możesz szybko i łatwo pobierać, buforować i wyświetlać obrazy z Cloud Storage, korzystając z naszej integracji z SDWebImage .

Najpierw dodaj FirebaseUI do swojego Podfile :

pod 'FirebaseStorageUI'

Następnie możesz załadować obrazy bezpośrednio z Cloud Storage do UIImageView :

Szybki

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

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

Zarządzaj pobranymi plikami

Oprócz rozpoczynania pobierania możesz wstrzymywać, wznawiać i anulować pobieranie, korzystając z metod pause , resume i cancel . Metody te wywołują pause , resume i cancel zdarzeń, które można zaobserwować.

Szybki

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

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

Monitoruj postęp pobierania

Możesz dołączyć obserwatorów do FIRStorageDownloadTask w celu monitorowania postępu pobierania. Dodanie obserwatora zwraca FIRStorageHandle , którego można użyć do usunięcia obserwatora.

Szybki

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

Cel C

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

Obserwatorów tych można zarejestrować w zdarzeniu FIRStorageTaskStatus :

Zdarzenie „FIRStorageTaskStatus”. Typowe użycie
FIRStorageTaskStatusResume To zdarzenie jest wywoływane, gdy zadanie rozpoczyna się lub wznawia pobieranie i jest często używane w połączeniu ze zdarzeniem FIRStorageTaskStatusPause .
FIRStorageTaskStatusProgress To zdarzenie jest uruchamiane za każdym razem, gdy dane są pobierane z Cloud Storage i może zostać użyte do wypełnienia wskaźnika postępu pobierania.
FIRStorageTaskStatusPause To zdarzenie jest uruchamiane za każdym razem, gdy pobieranie jest wstrzymane i często jest używane w połączeniu ze zdarzeniem FIRStorageTaskStatusResume .
FIRStorageTaskStatusSuccess To zdarzenie jest wywoływane po pomyślnym zakończeniu pobierania.
FIRStorageTaskStatusFailure To zdarzenie jest wywoływane, gdy pobieranie nie powiodło się. Sprawdź błąd, aby określić przyczynę niepowodzenia.

Po wystąpieniu zdarzenia obiekt FIRStorageTaskSnapshot jest przekazywany z powrotem. Ta migawka to niezmienny widok zadania w momencie wystąpienia zdarzenia. Obiekt ten zawiera następujące właściwości:

Nieruchomość Typ Opis
progress NSProgress Obiekt NSProgress zawierający postęp pobierania.
error NSError Błąd, który wystąpił podczas pobierania, jeśli wystąpił.
metadata FIRStorageMetadata nil pobrań.
task FIRStorageDownloadTask Zadanie to jest migawką, której można użyć do zarządzania ( pause , resume , cancel ) zadaniem.
reference FIRStorageReference Referencja, z której pochodzi to zadanie.

Możesz także usuwać obserwatorów indywidualnie, według statusu lub usuwając ich wszystkich.

Szybki

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

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

Aby zapobiec wyciekom pamięci, wszyscy obserwatorzy są usuwani po wystąpieniu FIRStorageTaskStatusSuccess lub FIRStorageTaskStatusFailure .

Obsługa błędów

Istnieje wiele powodów, dla których mogą wystąpić błędy podczas pobierania, na przykład nieistniejący plik lub brak uprawnień dostępu użytkownika do żądanego pliku. Więcej informacji na temat błędów można znaleźć w sekcji Obsługiwanie błędów w dokumentacji.

Pełny przykład

Poniżej przedstawiono pełny przykład pobierania do pliku lokalnego z obsługą błędów:

Szybki

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

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

Możesz także pobierać i aktualizować metadane plików przechowywanych w Cloud Storage.