Apple platformlarında Cloud Storage ile dosya indirme

Cloud Storage for Firebase, Firebase tarafından sağlanan ve yönetilen bir Cloud Storage paketinden dosyaları hızlı ve kolay bir şekilde indirmenize olanak tanır.

Referans Oluşturma

Bir dosyayı indirmek için önce indirmek istediğiniz dosyaya Cloud Storage referans oluşturun.

Alt yolları Cloud Storage paketinize ekleyerek referans oluşturabilir veya Cloud Storage içindeki bir nesneye referans veren mevcut bir gs:// ya da https:// URL'den referans oluşturabilirsiniz.

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

Dosyaları İndir

Referansınız olduğunda Cloud Storage dosyalarını üç şekilde indirebilirsiniz:

  1. Bellekteki NSData konumuna indirme
  2. Cihazdaki bir dosyayı temsil eden NSURL simgesine indirme
  3. Dosyayı online olarak temsil eden bir NSURL oluşturun.

Belleğe indirme

Dosyayı NSData yöntemini kullanarak bellekteki bir dataWithMaxSize:completion: nesnesine indirin. Bu yöntem, dosyaları hızlı bir şekilde indirmenin en kolay yoludur ancak dosyanızın tüm içeriğinin belleğe yüklenmesi gerekir. Uygulamanızın kullanılabilir belleğinden daha büyük bir dosya isteğinde bulunursanız uygulamanız çöker. Bellek sorunlarına karşı koruma sağlamak için maksimum boyutu uygulamanızın işleyebileceği bir değere ayarladığınızdan veya başka bir indirme yöntemi kullandığınızdan emin olun.

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

Yerel bir dosyaya indirme

writeToFile:completion: yöntemi, dosyayı doğrudan yerel bir cihaza indirir. Kullanıcılarınız dosyalara çevrimdışı erişmek veya dosyaları farklı bir uygulamada paylaşmak istiyorsa bu yöntemi kullanın. writeToFile:completion:, indirme işleminizi yönetmek ve yükleme durumunu izlemek için kullanabileceğiniz bir FIRStorageDownloadTask döndürür.

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

İndirme işleminizi etkin bir şekilde yönetmek istiyorsanız tamamlanma işleyicisi yerine writeToFile: yöntemini kullanabilir ve indirme görevini gözlemleyebilirsiniz. Daha fazla bilgi için İndirmeleri Yönetme başlıklı makaleyi inceleyin.

İndirme URL'si oluşturma

URL'lere dayalı bir indirme altyapınız varsa veya yalnızca paylaşmak için bir URL istiyorsanız downloadURLWithCompletion: referansında Cloud Storage yöntemini çağırarak bir dosyanın indirme URL'sini alabilirsiniz.

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

FirebaseUI ile resim indirme

FirebaseUI, standart kodu ortadan kaldırmak ve Google'ın en iyi uygulamalarını desteklemek için basit, özelleştirilebilir ve üretime hazır yerel mobil bağlamalar sağlar. FirebaseUI'ı kullanarak Cloud Storage'dan SDWebImage ile entegrasyonumuz sayesinde resimleri hızlı ve kolay bir şekilde indirebilir, önbelleğe alabilir ve görüntüleyebilirsiniz.

Öncelikle FirebaseUI'ı Podfile ekleyin:

pod 'FirebaseStorageUI'

Ardından, Cloud Storage uygulamasından doğrudan UIImageView içine resim yükleyebilirsiniz:

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

İndirilenleri yönetme

İndirme işlemlerini başlatmanın yanı sıra pause, resume ve cancel yöntemlerini kullanarak indirme işlemlerini duraklatabilir, devam ettirebilir ve iptal edebilirsiniz. Bu yöntemler, gözlemleyebileceğiniz pause, resume ve cancel etkinliklerini tetikler.

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

İndirme işleminin ilerleme durumunu izleme

İndirme işleminin ilerleme durumunu izlemek için FIRStorageDownloadTasklere gözlemciler ekleyebilirsiniz. Gözlemci eklemek, gözlemciyi kaldırmak için kullanılabilecek bir FIRStorageHandle döndürür.

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

Bu gözlemciler bir FIRStorageTaskStatus etkinliğine kaydedilebilir:

`FIRStorageTaskStatus` etkinliği Tipik Kullanım
FIRStorageTaskStatusResume Bu etkinlik, görev indirme işlemi başladığında veya devam ettiğinde tetiklenir ve genellikle FIRStorageTaskStatusPause etkinliğiyle birlikte kullanılır.
FIRStorageTaskStatusProgress Bu etkinlik, Cloud Storage adresinden veri indirildiğinde tetiklenir ve indirme ilerleme durumu göstergesini doldurmak için kullanılabilir.
FIRStorageTaskStatusPause Bu etkinlik, indirme işlemi her duraklatıldığında tetiklenir ve genellikle FIRStorageTaskStatusResume etkinliğiyle birlikte kullanılır.
FIRStorageTaskStatusSuccess Bu etkinlik, bir indirme işlemi başarıyla tamamlandığında tetiklenir.
FIRStorageTaskStatusFailure Bu etkinlik, indirme işlemi başarısız olduğunda tetiklenir. Hata nedenini belirlemek için hatayı inceleyin.

Bir etkinlik gerçekleştiğinde FIRStorageTaskSnapshot nesnesi geri iletilir. Bu anlık görüntü, etkinlik gerçekleştiği sırada görevle ilgili değişmez bir görünümü gösterir. Bu nesne aşağıdaki özellikleri içerir:

Özellik Tür Açıklama
progress NSProgress İndirme ilerleme durumunu içeren bir NSProgress nesnesi.
error NSError İndirme sırasında oluşan bir hata varsa.
metadata FIRStorageMetadata nil indirme işlemi.
task FIRStorageDownloadTask Bu, görevi yönetmek için kullanılabilecek bir anlık görüntüdür (pause, resume, cancel).
reference FIRStorageReference Bu görevin geldiği referans.

Gözlemcileri tek tek, duruma göre veya hepsini kaldırarak da kaldırabilirsiniz.

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

Bellek sızıntılarını önlemek için bir FIRStorageTaskStatusSuccess veya FIRStorageTaskStatusFailure işlemi gerçekleştiğinde tüm gözlemciler kaldırılır.

Hataları İşleme

İndirme sırasında hataların oluşmasının birkaç nedeni vardır. Örneğin, dosya mevcut olmayabilir veya kullanıcının istenen dosyaya erişme izni olmayabilir. Hatalar hakkında daha fazla bilgiyi dokümanların Hataları İşleme bölümünde bulabilirsiniz.

Tam Örnek

Aşağıda, hata işleme ile yerel bir dosyaya indirme işleminin tam bir örneği gösterilmektedir:

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

Ayrıca, Cloud Storage'da depolanan dosyalar için meta verileri alıp güncelleyebilirsiniz.