File Sharing API for Swift Native SDK
You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.
When a file is uploaded on a channel, it's stored and managed using a storage service, and associated with your key. Subscribers to that channel receive a file event which contains a file ID, filename, and optional description.
Send file
Upload the file to a specified channel.
This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.
For the last messaging step, send internally calls the publish method to publish a message on the channel.
The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.
File encryption
The cryptoModule set in PubNub config will be used for encryption unless you overwrite it using the custom parameter.
For more information, refer to Crypto module configuration.
Method(s)
1func send(
2 _ content: FileUploadContent,
3 channel: String,
4 remoteFilename: String,
5 publishRequest: PubNub.PublishFileRequest = PubNub.PublishFileRequest(),
6 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
7 uploadTask: @escaping (HTTPFileUploadTask) -> Void,
8 completion: ((Result<(task: HTTPFileUploadTask, file: PubNubLocalFile, publishedAt: Timetoken), Error>) -> Void)?
9)
| Parameter | Description |
|---|---|
content *Type: PubNub.FileUploadContentDefault: n/a | The content to be uploaded. |
channel *Type: String Default: n/a | The channel the file should be uploaded to. |
remoteFilename *Type: String Default: nil | The name of the content when uploaded. |
publishRequestType: PubNub.PublishFileRequestDefault: PubNub.PublishFileRequest() | The request configuration object when the file is published to PubNub. |
customType: PubNub.RequestConfigurationDefault: PubNub.RequestConfiguration | Custom configuration overrides when generating the File Upload URLRequest. |
uploadTaskType: (HTTPFileUploadTask) -> VoidDefault: { _ in } | The file upload task executing the upload; contains a reference to the actual URLSessionUploadTask. |
completionType: ((Result<(task: HTTPFileUploadTask, file: PubNubFile, publishedAt: Timetoken), Error>) -> Void)?Default: n/a | The async Resultof the method call. |
Details
1/// Content that can be uploaded as a File to PubNub
2enum FileUploadContent: CustomStringConvertible, CustomDebugStringConvertible {
3
4 /// A URL to an existing file
5 case file(url: URL)
6
7 /// The raw content of a file and the content type that best describes it
8 case data(_ data: Data, contentType: String?)
9
10 /// A stream of data, the content type of that stream, and the total length of the stream in bytes
11 case stream(_ stream: InputStream, contentType: String?, contentLength: Int)
12}
13
14/// Additional information that can be sent during a File publish
15struct PublishFileRequest {
show all 56 linesReturns
The completion handler will respond with a Result.
Success
A Tuple containing the HTTPFileUploadTask that completed, the PubNubFile or PubNubLocalFile that was uploaded, and the Timetoken when it was published.
1protocol PubNubLocalFile {
2
3 /// The local URL of the file
4 var fileURL: URL { get set }
5
6 /// If the local filenames change this can be used to track the remote filename
7 var remoteFilename: String { get }
8
9 /// The channel the file is associated with
10 var channel: String { get }
11
12 /// PubNub-generated ID for a file
13 var fileId: String { get }
14
15 /// User defined name for a file
show all 29 linesFailure
An Error describing the failure.
Sample code
Reference code
1
List channel files
Retrieve a list of files uploaded to a channel.
Method(s)
1func listFiles(
2 channel: String,
3 limit: UInt = 100,
4 next: String? = nil,
5 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
6 completion: ((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?
7)
| Parameter | Description |
|---|---|
channel *Type: String Default: n/a | Channel to get list of files. |
limitType: UIntDefault: 100 | Number of files to return. Minimum value is 1, and maximum is 100. |
nextType: String? Default: nil | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
customType: PubNub.RequestConfigurationDefault: PubNub.RequestConfiguration() | Custom configuration overrides when generating the File Upload URLRequest. |
completionType: ((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?Default: n/a | The async Result of the method call. |
Returns
The completion handler will respond with a Result.
Success
A Tuple list of PubNubFile objects, and the next page identifier (if one exists).
1protocol PubNubFile {
2
3 /// The channel the file is associated with
4 var channel: String { get }
5
6 /// PubNub-generated ID for a file
7 var fileId: String { get }
8
9 /// User defined name for a file
10 var filename: String { get }
11
12 /// Size, in bytes, of the stored file
13 var size: Int64 { get }
14
15 /// The MIME Type of the file
show all 23 linesFailure
An Error describing the failure.
Sample code
1
Get file URL
Generate a URL to download a file from the target channel.
Method(s)
1func generateFileDownloadURL(
2 channel: String,
3 fileId: String,
4 filename: String
5) throws -> URL
| Parameter | Description |
|---|---|
channel *Type: String | Name of channel to which the file has been uploaded. |
fileID *Type: String | Unique file identifier which has been assigned during file upload. |
filename *Type: String | Name under which the uploaded file is stored. |
Returns
The URL where the file can be downloaded.
Sample code
1
Download file
Download a file from the specified channel.
File encryption
If the cryptoModule is set in PubNub config, it will be used for decryption.
For more information, refer to Crypto module configuration.
Method(s)
1func download(
2 file: PubNubFile,
3 toFileURL localFileURL: URL,
4 resumeData: Data? = nil,
5 downloadTask: @escaping (HTTPFileDownloadTask) -> Void,
6 completion: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?
7)
| Parameter | Description |
|---|---|
file *Type: PubNubFileDefault: n/a | The file that should be downloaded. |
toFileURL *Type: URL Default: n/a | The file URL where the file should be downloaded to. This is NOT the URL returned from generateFileDownloadURL. |
resumeDataType: Data?Default: nil | A data object that provides the data necessary to resume a download. |
downloadTaskType: (HTTPFileDownloadTask) -> VoidDefault: { _ in } | The file upload task executing the upload; contains a reference to the actual URLSessionDownloadTask. |
completionType: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?Default: n/a | The async Result of the method call. |
Returns
The completion handler will respond with an instance of Result.
Success
A Tuple containing the HTTPFileDownloadTaskthat completed and the PubNubLocalFile that was downloaded. The fileURL of this object might be different from the toFileURL in the request if a file already exists at that location.
1class HTTPFileDownloadTask {
2
3 /// The underlying URLSessionTask that is being processed
4 var urlSessionTask: URLSessionTask { get }
5
6 /// A representation of the overall task progress
7 var progress: Progress { get }
8
9 /// The background identifier of the URLSession that is processing this task
10 var sessionIdentifier: String? { get }
11
12 /// An error object that indicates why the task failed
13 var error: Error? { get }
14
15 /// The server's response to the currently active request
show all 20 lines1protocol PubNubLocalFile {
2
3 /// The local URL of the file
4 var fileURL: URL { get set }
5
6 /// If the local filename changes this can be used to track the remote filename
7 var remoteFilename: String { get }
8
9 /// The channel the file is associated with
10 var channel: String { get }
11
12 /// PubNub-generated ID for a file
13 var fileId: String { get }
14
15 /// User defined name for a file
show all 29 linesFailure
An Error describing the failure.
Sample code
1
Resume download
Downloads can be paused and resumed at a later time under certain conditions. See Pausing and Resuming Downloads and cancel(byProducingResumeData:)
If you were given resumeData you can use the following example to try and resume your download; otherwise you can restart a new download.
1
Custom URLSession
By default, the PubNub instance will use a background configured URLSession. This will allow the download to continue while the application is not in the foreground. For more information, see Apple's documentation on Downloading Files in the Background
1
Delete file
Delete a file from the specified channel.
Method(s)
1func remove(
2 fileId: String,
3 filename: String,
4 channel: String,
5 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
6 completion: ((Result<(channel: String, fileId: String), Error>) -> Void)?
7)
| Parameter | Description |
|---|---|
fileId *Type: String Default: n/a | Unique file identifier which has been assigned during file upload. |
filename *Type: String Default: n/a | Name under which the uploaded file is stored. |
channel *Type: String Default: n/a | Channel the file was sent to. |
customType: PubNub.RequestConfigurationDefault: PubNub.RequestConfiguration() | Custom configuration overrides when generating the File Download URLRequest. |
completionType: ((Result<(channel: String, fileId: String), Error>) -> Void)?Default: n/a | The async Result of the method call. |
Returns
The completion handler will respond with an instance of Result.
Success
A Tuple containing the channelthat completed and the fileId of the removed file.
Failure
An Error describing the failure.
Sample code
1
Publish file message
Publish the uploaded file message to a specified channel.
This method is called internally by send as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.
This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.
You can call this method when send fails and returns the status.operation === PNPublishFileMessageOperation error.
In that case, you can use the data from the status object to try again and use publish to manually resend a file message to a channel without repeating the upload step.
Method(s)
1func publish(
2 file: PubNubFile,
3 request: PublishFileRequest,
4 completion: ((Result<Timetoken, Error>) -> Void)?
5)
| Parameter | Description |
|---|---|
file *Type: PubNubFileDefault: n/a | The PubNubFile representing the uploaded file. |
request *Type: PubNub.PublishFileRequestDefault: n/a | Additional information that can be sent during a File publish. |
completionType: ((Result<Timetoken, Error>) -> Void)?Default: n/a | The async Result of the method call. |
PubNub.PublishFileRequest
| Parameter | Description |
|---|---|
additionalMessage *Type: JSONCodable?Default: nil | The optional message to include alongside the File information. |
customMessageTypeType: String?Default: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-. Examples: text, action, poll. |
storeType: Bool?Default: nil | If true the published message is stored in history. |
ttlType: Int?Default: nil | Set a per message time to live in storage. |
metaType: JSONCodable?Default: nil | Additional metadata to publish alongside the file. |
customRequestConfigType: PubNub.RequestConfigurationDefault: PubNub.RequestConfiguration? | Custom configuration overrides for this request. |
Returns
The completion handler will respond with an instance of Result.
Success
A Timetoken of the published message.
Failure
An Error describing the failure.
Sample code
1