Files
Uploading, managing, and downloading files.
Info
Before working with files, follow our Getting Started Guide. It will show you how to set up your project to work with PrivMX Bridge.
The sample code on this page is based on the initial assumptions.
All policies in the following examples can be build with Policy Builders, according to Policies overview.
publicMeta
and privateMeta
fields in files support any kind of data formats encoded to byte arrays.
Examples in this section use JSON format serialization, which is available directly in Swift.
Assumptions
In further examples, the following structures are used:
struct FilePrivateMeta:Codable{
let name: String
let mimetype: String
}
Uploading Files
Uploading file to a Store in the most basic way:
let storeID = "STORE_ID"
guard let fileContentData = "Text file content".data(using: .utf8 ) else {return}
guard let storeFileHandle = try? endpointSession?.storeApi?.createFile(
in: storeID,
withPublicMeta: Data(),
withPrivateMeta: Data(),
ofSize: Int64(fileContentData.count))
else {return}
try? endpointSession?.storeApi?.writeToFile(withHandle: storeFileHandle, uploading: fileContentData)
Getting Files
Fetching the most recent files in given Store:
let startIndex:Int64 = 0
let pageSize:Int64 = 100
let storeId = "STORE_ID"
guard let pagingList = try? endpointSession?.storeApi?
.listFiles(
from:storeId,
basedOn: .init(skip: startIndex, limit: pageSize, sortOrder: .desc)) else {return}
let files =
pagingList.readItems.map { $0 }
Managing Files
var fileID = "FILE_ID"
guard let file = try? endpointSession?.storeApi?
.getFile(fileID) else {return}
let newFilePrivateMeta = FilePrivateMeta(name: "New Filename.txt", mimetype: "text/plain")
guard let newFilePrivateMetaData = try? JSONEncoder().encode(newFilePrivateMeta) else {return}
guard let filePublicMetaData = file.publicMeta.getData() else {return}
try? endpointSession?.storeApi?
.updateFile(fileID,
replacingPublicMeta: filePublicMetaData,
replacingPrivateMeta: newFilePrivateMetaData,
replacingSize: file.size)
Downloading Files
Downloading a file from the Store and saving it by chunk (defined by size var) to Data():
let fileId = "FILE_ID"
guard let handle = try? endpointSession?.storeApi?.openFile(fileId) else {return}
guard let file = try? endpointSession?.storeApi?.getFile(fileId) else {return}
_ = try? endpointSession?.storeApi?.readFromFile(withHandle: handle, length: file.size)
_ = try? endpointSession?.storeApi?.closeFile(withHandle: handle)