Scaricare file con Cloud Storage sulle piattaforme Apple

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

Creazione di un riferimento

Per scaricare un file, devi prima creare un riferimento Cloud Storage al file che vuoi scaricare.

Puoi creare un riferimento aggiungendo percorsi secondari alla radice del bucket Cloud Storage oppure puoi creare un riferimento da un URL gs:// o https:// esistente che fa riferimento a un oggetto in 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"];
  

Scarica file

Una volta che hai un riferimento, puoi scaricare i file da Cloud Storage in tre modi:

  1. Download su NSData nella memoria
  2. Download in un NSURL che rappresenta un file sul dispositivo
  3. Generare un NSURL che rappresenti il file online

Download in memoria

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

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

Scarica in un file locale

Il metodo writeToFile:completion: scarica un file direttamente su un dispositivo locale. Utilizza questa opzione se gli utenti vogliono accedere al file offline o condividerlo in un'altra app. writeToFile:completion: restituisce un FIRStorageDownloadTask che puoi utilizzare per gestire il download e monitorare lo stato del caricamento.

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

Se vuoi gestire attivamente il download, puoi utilizzare il metodo writeToFile: e osservare l'attività di download, anziché utilizzare il gestore di completamento. Per saperne di più, consulta Gestire i download.

Generare un URL di download

Se disponi già di un'infrastruttura di download basata sugli URL o vuoi semplicemente un URL da condividere, puoi ottenere l'URL di download di un file chiamando il metodo downloadURLWithCompletion: su un riferimento 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'
  }
}];
    

Download di immagini con FirebaseUI

FirebaseUI fornisce binding per dispositivi mobili nativi semplici, personalizzabili e pronti 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 da Cloud Storage in modo rapido e semplice utilizzando la nostra integrazione con SDWebImage.

Innanzitutto, aggiungi FirebaseUI al tuo Podfile:

pod 'FirebaseStorageUI'

Poi puoi caricare le immagini direttamente da Cloud Storage in un 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];
    

Gestisci i download

Oltre ad avviare i download, puoi metterli in pausa, riprenderli e annullarli utilizzando i metodi pause, resume e cancel. Questi metodi generano eventi pause, resume e cancel che puoi osservare.

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

Monitorare l'avanzamento del download

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

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

Questi osservatori possono essere registrati a un evento FIRStorageTaskStatus:

Evento `FIRStorageTaskStatus` Utilizzo tipico
FIRStorageTaskStatusResume Questo evento viene attivato quando l'attività inizia o riprende il download e viene spesso utilizzato in combinazione con l'evento FIRStorageTaskStatusPause.
FIRStorageTaskStatusProgress Questo evento viene attivato 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 viene attivato ogni volta che il download viene messo in pausa e viene spesso utilizzato in combinazione con l'evento FIRStorageTaskStatusResume.
FIRStorageTaskStatusSuccess Questo evento viene attivato quando un download è stato completato correttamente.
FIRStorageTaskStatusFailure Questo evento viene attivato quando un download non è riuscito. Esamina l'errore per determinare il motivo dell'errore.

Quando si verifica un evento, viene restituito un oggetto FIRStorageTaskSnapshot. Questo snapshot è una visualizzazione immutabile dell'attività al momento dell'evento. Questo oggetto contiene le seguenti proprietà:

Proprietà Tipo Descrizione
progress NSProgress Un oggetto NSProgress contenente l'avanzamento del download.
error NSError Un errore verificatosi durante il download, se presente.
metadata FIRStorageMetadata nil sui download.
task FIRStorageDownloadTask L'attività di cui viene acquisita un'istantanea, 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 singolarmente, in base allo stato o rimuovendoli tutti.

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

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

Gestisci gli errori

Esistono diversi motivi per cui potrebbero verificarsi errori durante il download, tra cui l'assenza del file o l'utente non dispone dell'autorizzazione per accedere al file desiderato. Per ulteriori informazioni sugli errori, consulta la sezione Gestire gli errori della documentazione.

Esempio completo

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

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

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