Utiliser des métadonnées de fichiers avec Cloud Storage sur les plates-formes Apple
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Après avoir importé un fichier dans la référence Cloud Storage, vous pouvez également obtenir et mettre à jour les métadonnées du fichier (par exemple, pour modifier le type de contenu). Les fichiers peuvent également stocker des paires clé/valeur personnalisées avec des métadonnées de fichier supplémentaires.
Obtenir les métadonnées d'un fichier
Les métadonnées de fichier contiennent des propriétés courantes telles que name, size et contentType (souvent appelé type MIME), en plus de propriétés moins courantes comme contentDisposition et timeCreated. Ces métadonnées peuvent être récupérées à partir d'une référence Cloud Storage à l'aide de la méthode 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'}}];
Mettre à jour les métadonnées d'un fichier
Vous pouvez mettre à jour les métadonnées d'un fichier à tout moment après l'importation à l'aide de la méthode updateMetadata:withCompletion:. Pour en savoir plus sur les propriétés qui peuvent être mises à jour, consultez la liste complète. Seules les propriétés spécifiées dans les métadonnées sont mises à jour. Toutes les autres restent inchangées.
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}}];
Vous pouvez supprimer des propriétés de métadonnées modifiables en les définissant sur nil :
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{// ...}
Gérer les erreurs
Plusieurs raisons peuvent expliquer les erreurs lors de la récupération ou de la mise à jour des métadonnées, y compris l'inexistence du fichier ou l'absence d'autorisation de l'utilisateur pour accéder au fichier souhaité. Pour en savoir plus sur les erreurs, consultez la section Gérer les erreurs de la documentation.
Métadonnées personnalisées
Vous pouvez spécifier des métadonnées personnalisées sous la forme d'un NSDictionary contenant des propriétés NSString.
Swift
letmetadata=["customMetadata":["location":"Yosemite, CA, USA","activity":"Hiking"]]
Objective-C
NSDictionary*metadata=@{@"customMetadata":@{@"location":@"Yosemite, CA, USA",@"activity":@"Hiking"}};
Vous pouvez stocker des données spécifiques à l'application pour chaque fichier dans des métadonnées personnalisées, mais nous vous recommandons vivement d'utiliser une base de données (telle que Firebase Realtime Database) pour stocker et synchroniser ce type de données.
Propriétés des métadonnées de fichier
Vous trouverez ci-dessous la liste complète des propriétés de métadonnées d'un fichier :
Propriété
Type
Accessible en écriture
bucket
Chaîne
Non
generation
Chaîne
Non
metageneration
Chaîne
Non
fullPath
Chaîne
Non
name
Chaîne
Non
size
Int64
Non
timeCreated
Date
Non
updated
Date
Non
md5Hash
Chaîne
Oui
cacheControl
Chaîne
Oui
contentDisposition
Chaîne
Oui
contentEncoding
Chaîne
Oui
contentLanguage
Chaîne
Oui
contentType
Chaîne
Oui
customMetadata
[String: String]
Oui
Il est important de pouvoir importer, télécharger et modifier des fichiers, mais il est tout aussi important de pouvoir les supprimer. Découvrons comment supprimer des fichiers de Cloud Storage.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/05 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/05 (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."]]