Scarica file con Cloud Storage su piattaforme Apple

Cloud Storage for Firebase ti consente di scaricare file in modo rapido e semplice da un bucket Cloud Storage fornito e gestito da Firebase.

Crea un riferimento

Per scaricare un file, crea innanzitutto un riferimento Cloud Storage per il file che desideri scaricare.

Puoi creare un riferimento aggiungendo percorsi secondari alla radice del tuo bucket Cloud Storage oppure puoi creare un riferimento da un URL gs:// o https:// esistente che fa riferimento a un oggetto in Cloud Storage.

Veloce

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

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

Scaricare files

Una volta ottenuto un riferimento, puoi scaricare file da Cloud Storage in tre modi:

  1. Scarica in NSData in memoria
  2. Scarica in un NSURL che rappresenta un file sul dispositivo
  3. Genera un NSURL che rappresenta il file online

Scarica in memoria

Scaricare il file in un oggetto NSData in memoria utilizzando il metodo dataWithMaxSize:completion: Questo è il modo più semplice per scaricare rapidamente un file, ma è necessario caricare in memoria l'intero contenuto del file. Se richiedi un file più grande della memoria disponibile dell'app, l'app si bloccherà. Per proteggerti da problemi di memoria, assicurati di impostare la dimensione massima su qualcosa che sai che la tua app può gestire o utilizza un altro metodo di download.

Veloce

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

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

Scarica in un file locale

Il metodo writeToFile:completion: scarica un file direttamente su un dispositivo locale. Utilizzalo se i tuoi utenti desiderano avere accesso al file mentre sono offline o per condividerlo in un'altra app. writeToFile:completion: restituisce un FIRStorageDownloadTask che puoi utilizzare per gestire il download e monitorare lo stato del caricamento.

Veloce

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

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

Se desideri gestire attivamente il tuo download, puoi utilizzare il metodo writeToFile: e osservare l'attività di download, anziché utilizzare il gestore di completamento. Per ulteriori informazioni, vedere Gestire i download .

Genera un URL di download

Se disponi già di un'infrastruttura di download basata sugli URL o desideri semplicemente condividere un URL, puoi ottenere l'URL di download di un file chiamando il metodo downloadURLWithCompletion: su un riferimento Cloud Storage.

Veloce

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

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

Download di immagini con FirebaseUI

FirebaseUI fornisce associazioni mobili native semplici, personalizzabili e pronte per la produzione per eliminare il codice boilerplate e promuovere le best practice di Google. Utilizzando FirebaseUI puoi scaricare, memorizzare nella cache e visualizzare immagini in modo rapido e semplice da Cloud Storage utilizzando la nostra integrazione con SDWebImage .

Innanzitutto, aggiungi FirebaseUI al tuo Podfile :

pod 'FirebaseStorageUI'

Quindi puoi caricare le immagini direttamente da Cloud Storage in UIImageView :

Veloce

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

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

Gestisci i download

Oltre ad avviare i download, puoi mettere in pausa, riprendere e annullare i download utilizzando i metodi pause , resume e cancel . Questi metodi generano eventi pause , resume e cancel che puoi osservare.

Veloce

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

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

Monitorare l'avanzamento del download

È possibile allegare osservatori a FIRStorageDownloadTask per monitorare l'avanzamento del download. L'aggiunta di un osservatore restituisce un FIRStorageHandle che può essere utilizzato per rimuovere l'osservatore.

Veloce

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

Obiettivo-C

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

Questi osservatori possono essere registrati in un evento FIRStorageTaskStatus :

Evento "FIRStorageTaskStatus". Utilizzo tipico
FIRStorageTaskStatusResume Questo evento si attiva quando l'attività avvia o riprende il download e viene spesso utilizzato insieme all'evento FIRStorageTaskStatusPause .
FIRStorageTaskStatusProgress Questo evento si attiva ogni volta che i dati vengono scaricati da Cloud Storage e può essere utilizzato per popolare un indicatore di avanzamento del download.
FIRStorageTaskStatusPause Questo evento si attiva ogni volta che il download viene sospeso e viene spesso utilizzato insieme all'evento FIRStorageTaskStatusResume .
FIRStorageTaskStatusSuccess Questo evento si attiva quando un download viene completato correttamente.
FIRStorageTaskStatusFailure Questo evento si attiva quando un download non riesce. Ispezionare l'errore per determinare il motivo dell'errore.

Quando si verifica un evento, viene restituito un oggetto FIRStorageTaskSnapshot . Questa istantanea è una visualizzazione immutabile dell'attività nel momento in cui si è verificato l'evento. Questo oggetto contiene le seguenti proprietà:

Proprietà Tipo Descrizione
progress NSProgress Un oggetto NSProgress contenente l'avanzamento del download.
error NSError Un errore che si è verificato durante il download, se presente.
metadata FIRStorageMetadata nil sui download.
task FIRStorageDownloadTask Si tratta di un'istantanea dell'attività che può essere utilizzata per gestire ( pause , resume , cancel ) l'attività.
reference FIRStorageReference Il riferimento da cui proviene questa attività.

Puoi anche rimuovere gli osservatori, individualmente, per stato o rimuovendoli tutti.

Veloce

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

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

Per evitare perdite di memoria, tutti gli osservatori vengono rimossi dopo che si verifica un FIRStorageTaskStatusSuccess o FIRStorageTaskStatusFailure .

Gestire gli errori

Esistono diversi motivi per cui potrebbero verificarsi errori durante il download, incluso il file inesistente o l'utente che non dispone dell'autorizzazione per accedere al file desiderato. Ulteriori informazioni sugli errori sono disponibili nella sezione Gestione degli errori della documentazione.

Esempio completo

Di seguito è riportato un esempio completo di download in un file locale con gestione degli errori:

Veloce

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

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

Puoi anche ottenere e aggiornare i metadati per i file archiviati in Cloud Storage.