Buka konsol

Mengupload File di iOS

Cloud Storage memungkinkan developer untuk mengupload file dengan cepat dan mudah ke bucket Google Cloud Storage yang disediakan dan dikelola oleh Firebase.

Membuat Referensi

Untuk mengupload file, buat referensi Cloud Storage terlebih dahulu ke lokasi tempat Anda ingin mengupload file di Cloud Storage.

Anda bisa membuat referensi dengan menambahkan lokasi turunan ke root penyimpanan:

Swift

// Create a root reference
let storageRef = storage.reference()

// Create a reference to "mountains.jpg"
let mountainsRef = storageRef.child("mountains.jpg")

// Create a reference to 'images/mountains.jpg'
let mountainImagesRef = storageRef.child("images/mountains.jpg")

// While the file names are the same, the references point to different files
mountainsRef.name == mountainImagesRef.name;            // true
mountainsRef.fullPath == mountainImagesRef.fullPath;    // false    

Objective-C

// Create a root reference
FIRStorageReference *storageRef = [storage reference];

// Create a reference to "mountains.jpg"
FIRStorageReference *mountainsRef = [storageRef child:@"mountains.jpg"];

// Create a reference to 'images/mountains.jpg'
FIRStorageReference *mountainImagesRef = [storageRef child:@"images/mountains.jpg"];

// While the file names are the same, the references point to different files
[mountainsRef.name isEqualToString:mountainImagesRef.name];         // true
[mountainsRef.fullPath isEqualToString:mountainImagesRef.fullPath]; // false  

Anda tidak bisa mengupload data dengan referensi ke root bucket Google Cloud Storage. Referensi Anda harus mengarah ke URL turunan.

Mengupload File

Setelah memiliki referensi, Anda bisa mengupload file ke Cloud Storage dengan dua cara:

  1. Mengupload dari data di memori
  2. Mengupload dari URL yang mewakili file pada perangkat

Mengupload dari data di memori

Metode putData:metadata:completion: adalah cara termudah untuk mengupload file ke Cloud Storage. putData:metadata:completion: mengambil objek NSData dan menampilkan FIRStorageUploadTask, yang dapat Anda gunakan untuk mengelola upload dan memantau statusnya.

Swift

// Data in memory
let data = Data()

// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")

// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(data, metadata: nil) { (metadata, error) in
  guard let metadata = metadata else {
    // Uh-oh, an error occurred!
    return
  }
  // Metadata contains file metadata such as size, content-type.
  let size = metadata.size
  // You can also access to download URL after upload.
  riversRef.downloadURL { (url, error) in
    guard let downloadURL = url else {
      // Uh-oh, an error occurred!
      return
    }
  }
}    

Objective-C

// Data in memory
NSData *data = [NSData dataWithContentsOfFile:@"rivers.jpg"];

// Create a reference to the file you want to upload
FIRStorageReference *riversRef = [storageRef child:@"images/rivers.jpg"];

// Upload the file to the path "images/rivers.jpg"
FIRStorageUploadTask *uploadTask = [riversRef putData:data
                                             metadata:nil
                                           completion:^(FIRStorageMetadata *metadata,
                                                        NSError *error) {
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Metadata contains file metadata such as size, content-type, and download URL.
    int size = metadata.size;
    // You can also access to download URL after upload.
    [riversRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
      if (error != nil) {
        // Uh-oh, an error occurred!
      } else {
        NSURL *downloadURL = URL;
      }
    }];
  }
}];  

Mengupload dari file lokal

Anda dapat mengupload file lokal pada perangkat, seperti foto dan video dari kamera, dengan metode putFile:metadata:completion:. putFile:metadata:completion: mengambil NSURL dan menampilkan FIRStorageUploadTask, yang dapat Anda gunakan untuk mengelola upload dan memantau statusnya.

Swift

// File located on disk
let localFile = URL(string: "path/to/image")!

// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")

// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putFile(from: localFile, metadata: nil) { metadata, error in
  guard let metadata = metadata else {
    // Uh-oh, an error occurred!
    return
  }
  // Metadata contains file metadata such as size, content-type.
  let size = metadata.size
  // You can also access to download URL after upload.
  storageRef.downloadURL { (url, error) in
    guard let downloadURL = url else {
      // Uh-oh, an error occurred!
      return
    }
  }
}    

Objective-C

// File located on disk
NSURL *localFile = [NSURL URLWithString:@"path/to/image"];

// Create a reference to the file you want to upload
FIRStorageReference *riversRef = [storageRef child:@"images/rivers.jpg"];

// Upload the file to the path "images/rivers.jpg"
FIRStorageUploadTask *uploadTask = [riversRef putFile:localFile metadata:nil completion:^(FIRStorageMetadata *metadata, NSError *error) {
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Metadata contains file metadata such as size, content-type, and download URL.
    int size = metadata.size;
    // You can also access to download URL after upload.
    [riversRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
      if (error != nil) {
        // Uh-oh, an error occurred!
      } else {
        NSURL *downloadURL = URL;
      }
    }];
  }
}];  

Jika ingin mengelola upload secara aktif, Anda dapat menggunakan metode putData: atau putFile: untuk mengamati tugas upload, dan bukan menggunakan penangan penyelesaian. Lihat Mengelola Upload untuk informasi lebih lanjut.

Menambahkan Metadata File

Anda juga dapat menyertakan metadata ketika mengupload file. Metadata ini berisi properti metadata file standar, seperti name, size, dan contentType (umumnya dikenal sebagai jenis MIME). Metode putFile: secara otomatis menyimpulkan jenis konten dari ekstensi nama file NSURL, tetapi Anda bisa mengganti jenis yang terdeteksi otomatis dengan menetapkan contentType dalam metadata. Jika contentType tidak ada dan Cloud Storage tidak dapat menyimpulkan jenis konten default dari ekstensi file, Cloud Storage akan menggunakan application/octet-stream. Baca bagian Menggunakan Metadata File untuk mengetahui informasi lebih lanjut mengenai metadata file.

Swift

// Create storage reference
let mountainsRef = storageRef.child("images/mountains.jpg")

// Create file metadata including the content type
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"

// Upload data and metadata
mountainsRef.putData(data, metadata: metadata)

// Upload file and metadata
mountainsRef.putFile(from: localFile, metadata: metadata)    

Objective-C

// Create storage reference
FIRStorageReference *mountainsRef = [storageRef child:@"images/mountains.jpg"];

// Create file metadata including the content type
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = @"image/jpeg";

// Upload data and metadata
FIRStorageUploadTask *uploadTask = [mountainsRef putData:data metadata:metadata];

// Upload file and metadata
uploadTask = [mountainsRef putFile:localFile metadata:metadata];  

Mengelola Upload

Selain memulai upload, Anda dapat menjeda, melanjutkan, dan membatalkan upload menggunakan metode pause, resume, dan cancel. Metode ini melaporkan peristiwa pause, resume, dan cancel. Jika upload dibatalkan, proses upload akan gagal dengan pesan error yang menunjukkan bahwa upload dibatalkan.

Swift

// Start uploading a file
let uploadTask = storageRef.putFile(from: localFile)

// Pause the upload
uploadTask.pause()

// Resume the upload
uploadTask.resume()

// Cancel the upload
uploadTask.cancel()    

Objective-C

// Start uploading a file
FIRStorageUploadTask *uploadTask = [storageRef putFile:localFile];

// Pause the upload
[uploadTask pause];

// Resume the upload
[uploadTask resume];

// Cancel the upload
[uploadTask cancel];  

Memantau Kemajuan Upload

Anda bisa memasang observer ke FIRStorageUploadTask untuk memantau kemajuan upload. Jika observer ditambahkan, FIRStorageHandle akan ditampilkan, yang dapat digunakan untuk menghapus observer tersebut.

Swift

// Add a progress observer to an upload task
let observer = uploadTask.observe(.progress) { snapshot in
  // A progress event occured
}    

Objective-C

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

Observer ini dapat ditambahkan ke peristiwa FIRStorageTaskStatus:

Peristiwa FIRStorageTaskStatus Penggunaan Standar
FIRStorageTaskStatusResume Peristiwa ini dijalankan saat memulai tugas atau melanjutkan upload dan sering kali digunakan bersamaan dengan peristiwa FIRStorageTaskStatusPause.
FIRStorageTaskStatusProgress Peristiwa ini dijalankan setiap kali data diupload ke Cloud Storage dan dapat digunakan untuk mengisi indikator kemajuan upload.
FIRStorageTaskStatusPause Peristiwa ini dijalankan setiap kali upload dijeda dan sering kali digunakan bersamaan dengan peristiwa FIRStorageTaskStatusResume.
FIRStorageTaskStatusSuccess Peristiwa ini dijalankan ketika upload telah selesai dengan sukses.
FIRStorageTaskStatusFailure Peristiwa ini dijalankan ketika upload gagal. Periksa error untuk mengetahui alasan kegagalan.

Saat sebuah peristiwa terjadi, objek FIRStorageTaskSnapshot akan diterima. Snapshot ini adalah tampilan tetap dari tugas pada saat peristiwa tersebut terjadi. Objek ini berisi properti berikut:

Properti Jenis Deskripsi
progress NSProgress Objek NSProgress berisi kemajuan upload.
error NSError Error yang terjadi ketika mengupload jika ada.
metadata FIRStorageMetadata Berisi metadata yang diupload saat proses upload berlangsung. Setelah peristiwa FIRTaskStatusSuccess, berisi metadata file yang diupload.
task FIRStorageUploadTask Tugas yang menjadi snapshot-nya, yang bisa digunakan untuk mengelola tugas (pause, resume, cancel).
reference FIRStorageReference Referensi tempat tugas ini berasal.

Anda juga dapat menghapus observer, baik satu per satu, berdasarkan status, atau menghapus semuanya.

Swift

// Create a task listener handle
let observer = uploadTask.observe(.progress) { snapshot in
  // A progress event occurred
}

// Remove an individual observer
uploadTask.removeObserver(withHandle: observer)

// Remove all observers of a particular status
uploadTask.removeAllObservers(for: .progress)

// Remove all observers
uploadTask.removeAllObservers()    

Objective-C

// Create a task listener handle
FIRStorageHandle observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress
                                              handler:^(FIRStorageTaskSnapshot *snapshot) {
                                                // A progress event occurred
                                              }];

// Remove an individual observer
[uploadTask removeObserverWithHandle:observer];

// Remove all observers of a particular status
[uploadTask removeAllObserversForStatus:FIRStorageTaskStatusProgress];

// Remove all observers
[uploadTask removeAllObservers];  

Untuk mencegah kebocoran memori, semua observer akan dihapus setelah FIRStorageTaskStatusSuccess atau FIRStorageTaskStatusFailure terjadi.

Penanganan Error

Ada sejumlah alasan penyebab terjadinya error saat upload, termasuk tidak adanya file lokal, atau pengguna tidak memiliki izin untuk mengupload file yang diinginkan. Anda dapat menemukan informasi lebih lanjut mengenai error di bagian Menangani Error pada dokumentasi.

Contoh Lengkap

Contoh lengkap upload dengan pemantauan kemajuan dan penanganan error ditampilkan di bawah ini:

Swift

// Local file you want to upload
let localFile = URL(string: "path/to/image")!

// Create the file metadata
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"

// Upload file and metadata to the object 'images/mountains.jpg'
let uploadTask = storageRef.putFile(from: localFile, metadata: metadata)

// Listen for state changes, errors, and completion of the upload.
uploadTask.observe(.resume) { snapshot in
  // Upload resumed, also fires when the upload starts
}

uploadTask.observe(.pause) { snapshot in
  // Upload paused
}

uploadTask.observe(.progress) { snapshot in
  // Upload reported progress
  let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
    / Double(snapshot.progress!.totalUnitCount)
}

uploadTask.observe(.success) { snapshot in
  // Upload completed successfully
}

uploadTask.observe(.failure) { snapshot in
  if let error = snapshot.error as? NSError {
    switch (StorageErrorCode(rawValue: error.code)!) {
    case .objectNotFound:
      // File doesn't exist
      break
    case .unauthorized:
      // User doesn't have permission to access file
      break
    case .cancelled:
      // User canceled the upload
      break

    /* ... */

    case .unknown:
      // Unknown error occurred, inspect the server response
      break
    default:
      // A separate error occurred. This is a good place to retry the upload.
      break
    }
  }
}    

Objective-C

// Local file you want to upload
NSURL *localFile = [NSURL URLWithString:@"path/to/image"];

// Create the file metadata
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = @"image/jpeg";

// Upload file and metadata to the object 'images/mountains.jpg'
FIRStorageUploadTask *uploadTask = [storageRef putFile:localFile metadata:metadata];

// Listen for state changes, errors, and completion of the upload.
[uploadTask observeStatus:FIRStorageTaskStatusResume handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload resumed, also fires when the upload starts
}];

[uploadTask observeStatus:FIRStorageTaskStatusPause handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload paused
}];

[uploadTask observeStatus:FIRStorageTaskStatusProgress handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload reported progress
  double percentComplete = 100.0 * (snapshot.progress.completedUnitCount) / (snapshot.progress.totalUnitCount);
}];

[uploadTask observeStatus:FIRStorageTaskStatusSuccess handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload completed successfully
}];

// Errors only occur in the "Failure" case
[uploadTask 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;
    }
  }
}];  

Setelah mengupload file, pelajari cara mendownloadnya dari Cloud Storage.