שימוש במטא-נתונים של קבצים ב-Cloud Storage בפלטפורמות של Apple
קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
אחרי שמעלים קובץ לCloud Storage, אפשר גם לקבל ולעדכן את המטא-נתונים של הקובץ, למשל כדי לעדכן את סוג התוכן. בנוסף, בקבצים אפשר לאחסן צמדי מפתח/ערך בהתאמה אישית עם מטא-נתונים נוספים של הקובץ.
אחזור מטא-נתונים של קובץ
המטא-נתונים של הקובץ מכילים מאפיינים נפוצים כמו name, size ו-contentType (שנקרא לעיתים קרובות סוג MIME), בנוסף למאפיינים פחות נפוצים כמו contentDisposition ו-timeCreated. אפשר לאחזר את המטא-נתונים האלה מהפניה Cloud Storage באמצעות השיטה 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'}}];
עדכון המטא-נתונים של הקובץ
אפשר לעדכן את המטא-נתונים של הקובץ בכל שלב אחרי שההעלאה של הקובץ מסתיימת באמצעות השיטה updateMetadata:withCompletion:. למידע נוסף על המאפיינים שאפשר לעדכן, אפשר לעיין ברשימה המלאה. רק המאפיינים שצוינו במטא-נתונים מתעדכנים,
כל השאר נשארים ללא שינוי.
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}}];
כדי למחוק מאפייני מטא-נתונים שאפשר לכתוב בהם, צריך להגדיר אותם ל-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{// ...}
טיפול בשגיאות
יכולות להיות כמה סיבות לשגיאות שמתרחשות כשמקבלים או מעדכנים מטא-נתונים, כולל קובץ שלא קיים או משתמש שאין לו הרשאה לגשת לקובץ הרצוי. מידע נוסף על שגיאות זמין בקטע Handle Errors במסמכים.
מטא-נתונים בהתאמה אישית
אפשר לציין מטא-נתונים בהתאמה אישית כ-NSDictionary שמכיל מאפיינים של NSString.
Swift
letmetadata=["customMetadata":["location":"Yosemite, CA, USA","activity":"Hiking"]]
Objective-C
NSDictionary*metadata=@{@"customMetadata":@{@"location":@"Yosemite, CA, USA",@"activity":@"Hiking"}};
אפשר לאחסן נתונים ספציפיים לאפליקציה לכל קובץ במטא-נתונים בהתאמה אישית, אבל מומלץ מאוד להשתמש במסד נתונים (כמו Firebase Realtime Database) כדי לאחסן ולסנכרן את סוג הנתונים הזה.
מאפייני המטא-נתונים של הקובץ
בהמשך מופיעה רשימה מלאה של מאפייני המטא-נתונים בקובץ:
נכס
סוג
ניתן לכתיבה
bucket
מחרוזת
לא
generation
מחרוזת
לא
metageneration
מחרוזת
לא
fullPath
מחרוזת
לא
name
מחרוזת
לא
size
Int64
לא
timeCreated
תאריך
לא
updated
תאריך
לא
md5Hash
מחרוזת
כן
cacheControl
מחרוזת
כן
contentDisposition
מחרוזת
כן
contentEncoding
מחרוזת
כן
contentLanguage
מחרוזת
כן
contentType
מחרוזת
כן
customMetadata
[String: String]
כן
העלאה, הורדה ועדכון של קבצים הם חשובים, אבל חשוב גם להיות מסוגלים להסיר אותם. במאמר הזה נסביר איך למחוק קבצים מ-Cloud Storage.
[[["התוכן קל להבנה","easyToUnderstand","thumb-up"],["התוכן עזר לי לפתור בעיה","solvedMyProblem","thumb-up"],["סיבה אחרת","otherUp","thumb-up"]],[["חסרים לי מידע או פרטים","missingTheInformationINeed","thumb-down"],["התוכן מורכב מדי או עם יותר מדי שלבים","tooComplicatedTooManySteps","thumb-down"],["התוכן לא עדכני","outOfDate","thumb-down"],["בעיה בתרגום","translationIssue","thumb-down"],["בעיה בדוגמאות/בקוד","samplesCodeIssue","thumb-down"],["סיבה אחרת","otherDown","thumb-down"]],["עדכון אחרון: 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."]]