Как создать ссылку на Cloud Storage на платформах Apple

Ваши файлы хранятся в сегменте Cloud Storage. Файлы в этом сегменте представлены в виде иерархической структуры, как и в файловой системе на локальном жестком диске или в данных Firebase Realtime Database. Создав ссылку на файл, приложение получает к нему доступ. Эти ссылки затем можно использовать для загрузки или скачивания данных, получения или обновления метаданных или удаления файла. Ссылка может указывать на определенный файл или на узел более высокого уровня в иерархии.

Если вы использовали Firebase Realtime Database, эти пути должны быть вам хорошо знакомы. Однако данные файлов хранятся в Cloud Storage, а не в Realtime Database.

Создание ссылки

Создайте ссылку, чтобы загрузить, скачать или удалить файл, а также получить или обновить его метаданные. Ссылку можно рассматривать как указатель на файл в облаке. Ссылки не занимают много места, поэтому вы можете создавать их в любом количестве. Их также можно использовать повторно для нескольких операций.

Цифровые отпечатки создаются с помощью сервиса FirebaseStorage и вызова его метода reference.

Swift

// Get a reference to the storage service using the default Firebase App
let storage = Storage.storage()

// Create a storage reference from our storage service
let storageRef = storage.reference()
    

Objective-C

// Get a reference to the storage service using the default Firebase App
FIRStorage *storage = [FIRStorage storage];

// Create a storage reference from our storage service
FIRStorageReference *storageRef = [storage reference];
    

Вы можете создать ссылку на местоположение ниже в дереве, например 'images/space.jpg', используя метод child для существующей ссылки.

Swift

// Create a child reference
// imagesRef now points to "images"
let imagesRef = storageRef.child("images")

// Child references can also take paths delimited by '/'
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"
var spaceRef = storageRef.child("images/space.jpg")

// This is equivalent to creating the full reference
let storagePath = "\(your_firebase_storage_bucket)/images/space.jpg"
spaceRef = storage.reference(forURL: storagePath)
    

Objective-C

// Create a child reference
// imagesRef now points to "images"
FIRStorageReference *imagesRef = [storageRef child:@"images"];

// Child references can also take paths delimited by '/'
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"
FIRStorageReference *spaceRef = [storageRef child:@"images/space.jpg"];

// This is equivalent to creating the full reference
spaceRef = [storage referenceForURL:@"gs://<your-firebase-storage-bucket>/images/space.jpg"];
     

Для перемещения вверх по иерархии файлов можно также использовать методы parent и root. parent – переход на один уровень вверх, а root – на самый верхний уровень.

Swift

// Parent allows us to move to the parent of a reference
// imagesRef now points to 'images'
let imagesRef = spaceRef.parent()

// Root allows us to move all the way back to the top of our bucket
// rootRef now points to the root
let rootRef = spaceRef.root()
    

Objective-C

// Parent allows us to move to the parent of a reference
// imagesRef now points to 'images'
imagesRef = [spaceRef parent];

// Root allows us to move all the way back to the top of our bucket
// rootRef now points to the root
FIRStorageReference *rootRef = [spaceRef root];
    

child, parent и root можно объединять в цепочки, поскольку каждый из них возвращает ссылку. Исключение – parent root, который равен nil.

Swift

// References can be chained together multiple times
// earthRef points to "images/earth.jpg"
let earthRef = spaceRef.parent()?.child("earth.jpg")

// nilRef is nil, since the parent of root is nil
let nilRef = spaceRef.root().parent()
    

Objective-C

// References can be chained together multiple times
// earthRef points to "images/earth.jpg"
FIRStorageReference *earthRef = [[spaceRef parent] child:@"earth.jpg"];

// nilRef is nil, since the parent of root is nil
FIRStorageReference *nilRef = [[spaceRef root] parent];
    

Свойства цифрового отпечатка

Вы можете проверить ссылки, чтобы лучше понять, на какие файлы они указывают, используя свойства fullPath, name и bucket. Эти свойства получают полный путь к файлу, его имя и сегмент.

Swift

// Reference's path is: "images/space.jpg"
// This is analogous to a file path on disk
spaceRef.fullPath

// Reference's name is the last segment of the full path: "space.jpg"
// This is analogous to the file name
spaceRef.name

// Reference's bucket is the name of the storage bucket where files are stored
spaceRef.bucket
    

Objective-C

// Reference's path is: "images/space.jpg"
// This is analogous to a file path on disk
spaceRef.fullPath;

// Reference's name is the last segment of the full path: "space.jpg"
// This is analogous to the file name
spaceRef.name;

// Reference's bucket is the name of the storage bucket where files are stored
spaceRef.bucket;
    

Ограничения на использование цифровых отпечатков

Пути и названия могут содержать любые допустимые символы Unicode, но с некоторыми ограничениями:

  1. Общая длина reference.fullPath должна быть от 1 до 1024 байт в кодировке UTF-8.
  2. В названиях запрещены управляющие символы ASCII (символ возврата каретки и перевод строки).
  3. Не используйте символы #, [, ], * и ?, так как они не поддерживаются в некоторых инструментах, например в Firebase Realtime Database и gsutil.

Полный пример

Swift

// Points to the root reference
let storageRef = Storage.storage().reference()

// Points to "images"
let imagesRef = storageRef.child("images")

// Points to "images/space.jpg"
// Note that you can use variables to create child values
let fileName = "space.jpg"
let spaceRef = imagesRef.child(fileName)

// File path is "images/space.jpg"
let path = spaceRef.fullPath

// File name is "space.jpg"
let name = spaceRef.name

// Points to "images"
let images = spaceRef.parent()
    

Objective-C

// Points to the root reference
FIRStorageReference *storageRef = [[FIRStorage storage] reference];

// Points to "images"
FIRStorageReference *imagesRef = [storageRef child:@"images"];

// Points to "images/space.jpg"
// Note that you can use variables to create child values
NSString *fileName = @"space.jpg";
FIRStorageReference *spaceRef = [imagesRef child:fileName];

// File path is "images/space.jpg"
NSString *path = spaceRef.fullPath;

// File name is "space.jpg"
NSString *name = spaceRef.name;

// Points to "images"
imagesRef = [spaceRef parent];
    

Теперь давайте узнаем, как загружать файлы в Cloud Storage.