Как создать ссылку на 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 (CR и LF).
  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.