Usar metadados de arquivos com o Cloud Storage em plataformas da Apple
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Depois de fazer upload de um arquivo para a referência do Cloud Storage, também é possível acessar e atualizar os metadados do arquivo para, por exemplo, atualizar o tipo do conteúdo. Os arquivos
também podem armazenar os pares de chave/valor personalizados com metadados adicionais.
Acessar metadados de arquivo
Os metadados de arquivos contêm propriedades comuns, que muitas vezes são chamadas de tipo MIME, como name, size e contentType, além de outras menos comuns, como contentDisposition e timeCreated. Esses metadados podem ser recuperados de uma referência do Cloud Storage usando o método metadataWithCompletion:.
Swift
// Create reference to the file whose metadata we want to retrieveletforestRef=storageRef.child("images/forest.jpg")// Get metadata propertiesdo{letmetadata=tryawaitforestRef.getMetadata()}catch{// ...}
Objective-C
// Create reference to the file whose metadata we want to retrieveFIRStorageReference*forestRef=[storageRefchild:@"images/forest.jpg"];// Get metadata properties[forestRefmetadataWithCompletion:^(FIRStorageMetadata*metadata,NSError*error){if(error!=nil){// Uh-oh, an error occurred!}else{// Metadata now contains the metadata for 'images/forest.jpg'}}];
Atualizar metadados de arquivos
Com o método updateMetadata:withCompletion:, é possível atualizar os metadados de arquivos
após a conclusão do upload. Consulte a
lista completa para saber mais sobre as propriedades
que podem ser atualizadas. Somente as propriedades especificadas nos metadados são atualizadas. As demais não são modificadas.
Swift
// Create reference to the file whose metadata we want to changeletforestRef=storageRef.child("images/forest.jpg")// Create file metadata to updateletnewMetadata=StorageMetadata()newMetadata.cacheControl="public,max-age=300"newMetadata.contentType="image/jpeg"// Update metadata propertiesdo{letupdatedMetadata=tryawaitforestRef.updateMetadata(newMetadata)}catch{// ...}
Objective-C
// Create reference to the file whose metadata we want to changeFIRStorageReference*forestRef=[storageRefchild:@"images/forest.jpg"];// Create file metadata to updateFIRStorageMetadata*newMetadata=[[FIRStorageMetadataalloc]init];newMetadata.cacheControl=@"public,max-age=300";newMetadata.contentType=@"image/jpeg";// Update metadata properties[forestRefupdateMetadata:newMetadatacompletion:^(FIRStorageMetadata*metadata,NSError*error){if(error!=nil){// Uh-oh, an error occurred!}else{// Updated metadata for 'images/forest.jpg' is returned}}];
Defina as propriedades de metadados graváveis como nil para que elas sejam excluídas:
Objective-C
FIRStorageMetadata*newMetadata=[[FIRStorageMetadataalloc]init];newMetadata.contentType=nil;// Delete the metadata property[forestRefupdateMetadata:newMetadatacompletion:^(FIRStorageMetadata*metadata,NSError*error){if(error!=nil){// Uh-oh, an error occurred!}else{// metadata.contentType should be nil}}];
Swift
letnewMetadata=StorageMetadata()newMetadata.contentType=nildo{// Delete the metadata propertyletupdatedMetadata=tryawaitforestRef.updateMetadata(newMetadata)}catch{// ...}
Lidar com erros
Podem ocorrer diferentes erros ao receber ou atualizar metadados, como arquivo inexistente ou usuário sem permissão de acesso ao arquivo desejado. Saiba mais sobre erros na seção
Tratar erros.
Metadados personalizados
É possível especificar metadados personalizados como um NSDictionary contendo propriedades NSString.
Swift
letmetadata=["customMetadata":["location":"Yosemite, CA, USA","activity":"Hiking"]]
Objective-C
NSDictionary*metadata=@{@"customMetadata":@{@"location":@"Yosemite, CA, USA",@"activity":@"Hiking"}};
É possível armazenar os dados específicos de app de cada arquivo nos metadados personalizados, mas recomendamos o uso de um banco de dados como o Firebase Realtime Database para armazenar e sincronizar esse tipo de dados.
Propriedades de metadados de arquivos
Veja abaixo uma lista completa de propriedades de metadados em um arquivo:
Propriedade
Tipo
Gravável
bucket
String
Não
generation
String
Não
metageneration
String
Não
fullPath
String
Não
name
String
Não
size
Int64
Não
timeCreated
Data
Não
updated
Data
Não
md5Hash
String
Sim
cacheControl
String
Sim
contentDisposition
String
Sim
contentEncoding
String
Sim
contentLanguage
String
Sim
contentType
String
Sim
customMetadata
[String: String]
Sim
Fazer download, upload e atualizar arquivos são tarefas importantes, mas poder removê-los também é essencial. Vamos aprender como excluir arquivos do Cloud Storage.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-03 UTC."],[],[],null,["\u003cbr /\u003e\n\nAfter uploading a file to Cloud Storage reference, you can also get\nand update the file metadata, for example to update the content type. Files\ncan also store custom key/value pairs with additional file metadata.\n| **Note:** By default, a Cloud Storage for Firebase bucket requires Firebase Authentication to perform any action on the bucket's data or files. You can change your Firebase Security Rules for Cloud Storage to [allow unauthenticated access for specific situations](/docs/storage/security/rules-conditions#public). However, for most situations, we strongly recommend [restricting access and setting up robust security rules](/docs/storage/security/get-started) (especially for production apps). Note that if you use Google App Engine and have a default Cloud Storage bucket with a name format of `*.appspot.com`, you may need to consider [how your security rules impact access to App Engine files](/docs/storage/gcp-integration#security-rules-and-app-engine-files).\n\nGet File Metadata\n\nFile metadata contains common properties such as `name`, `size`, and\n`contentType` (often referred to as MIME type) in addition to some less\ncommon ones like `contentDisposition` and `timeCreated`. This metadata can be\nretrieved from a Cloud Storage reference using\nthe `metadataWithCompletion:` method. \n\nSwift \n\n```swift\n// Create reference to the file whose metadata we want to retrieve\nlet forestRef = storageRef.child(\"images/forest.jpg\")\n\n// Get metadata properties\ndo {\n let metadata = try await forestRef.getMetadata()\n} catch {\n // ...\n}\n \n```\n\nObjective-C \n\n```objective-c\n// Create reference to the file whose metadata we want to retrieve\nFIRStorageReference *forestRef = [storageRef child:@\"images/forest.jpg\"];\n\n// Get metadata properties\n[forestRef metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {\n if (error != nil) {\n // Uh-oh, an error occurred!\n } else {\n // Metadata now contains the metadata for 'images/forest.jpg'\n }\n}];\n \n```\n\nUpdate File Metadata\n\nYou can update file metadata at any time after the file upload completes by\nusing the `updateMetadata:withCompletion:` method. Refer to the\n[full list](#file_metadata_properties) for more information on what properties\ncan be updated. Only the properties specified in the metadata are updated,\nall others are left unmodified. \n\nSwift \n\n```swift\n// Create reference to the file whose metadata we want to change\nlet forestRef = storageRef.child(\"images/forest.jpg\")\n\n// Create file metadata to update\nlet newMetadata = StorageMetadata()\nnewMetadata.cacheControl = \"public,max-age=300\"\nnewMetadata.contentType = \"image/jpeg\"\n\n// Update metadata properties\ndo {\n let updatedMetadata = try await forestRef.updateMetadata(newMetadata)\n} catch {\n // ...\n}\n \n```\n\nObjective-C \n\n```objective-c\n// Create reference to the file whose metadata we want to change\nFIRStorageReference *forestRef = [storageRef child:@\"images/forest.jpg\"];\n\n// Create file metadata to update\nFIRStorageMetadata *newMetadata = [[FIRStorageMetadata alloc] init];\nnewMetadata.cacheControl = @\"public,max-age=300\";\nnewMetadata.contentType = @\"image/jpeg\";\n\n// Update metadata properties\n[forestRef updateMetadata:newMetadata completion:^(FIRStorageMetadata *metadata, NSError *error){\n if (error != nil) {\n // Uh-oh, an error occurred!\n } else {\n // Updated metadata for 'images/forest.jpg' is returned\n }\n}];\n \n```\n\nYou can delete writable metadata properties by setting them to `nil`: \n\nObjective-C \n\n```objective-c\nFIRStorageMetadata *newMetadata = [[FIRStorageMetadata alloc] init];\nnewMetadata.contentType = nil;\n\n// Delete the metadata property\n[forestRef updateMetadata:newMetadata completion:^(FIRStorageMetadata *metadata, NSError *error){\n if (error != nil) {\n // Uh-oh, an error occurred!\n } else {\n // metadata.contentType should be nil\n }\n}];\n```\n\nSwift \n\n```swift\nlet newMetadata = StorageMetadata()\nnewMetadata.contentType = nil\n\ndo {\n // Delete the metadata property\n let updatedMetadata = try await forestRef.updateMetadata(newMetadata)\n} catch {\n // ...\n}\n```\n\nHandle Errors\n\nThere are a number of reasons why errors may occur on getting or updating\nmetadata, including the file not existing, or the user not having permission\nto access the desired file. More information on errors can be found in the\n[Handle Errors](/docs/storage/ios/handle-errors)\nsection of the docs.\n\nCustom Metadata\n\nYou can specify custom metadata as an `NSDictionary` containing `NSString`\nproperties. \n\nSwift \n\n```swift\nlet metadata = [\n \"customMetadata\": [\n \"location\": \"Yosemite, CA, USA\",\n \"activity\": \"Hiking\"\n ]\n]\n \n```\n\nObjective-C \n\n```objective-c\nNSDictionary *metadata = @{\n @\"customMetadata\": @{\n @\"location\": @\"Yosemite, CA, USA\",\n @\"activity\": @\"Hiking\"\n }\n};\n```\n\nYou can store app-specific data for each file in custom metadata, but we highly\nrecommend using a database (such as the\n[Firebase Realtime Database](/docs/database)) to store and synchronize this type of\ndata.\n\nFile Metadata Properties\n\nA full list of metadata properties on a file is available below:\n\n| Property | Type | Writable |\n|----------------------|--------------------|----------|\n| `bucket` | String | No |\n| `generation` | String | No |\n| `metageneration` | String | No |\n| `fullPath` | String | No |\n| `name` | String | No |\n| `size` | Int64 | No |\n| `timeCreated` | Date | No |\n| `updated` | Date | No |\n| `md5Hash` | String | Yes |\n| `cacheControl` | String | Yes |\n| `contentDisposition` | String | Yes |\n| `contentEncoding` | String | Yes |\n| `contentLanguage` | String | Yes |\n| `contentType` | String | Yes |\n| `customMetadata` | \\[String: String\\] | Yes |\n\n| **Note:** at present, setting the `md5Hash` property on upload doesn't affect the upload, as hash verification is not yet implemented.\n\nUploading, downloading, and updating files is important, but so is being able\nto remove them. Let's learn how to\n[delete files](/docs/storage/ios/delete-files)\nfrom Cloud Storage."]]