File Sharing API for Swift Native SDK

Allows users to upload and share files. You can upload any file of up to 5 MB in size. This feature is commonly used in social apps to share images, or in medical apps to share medical records for patients.

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)

send(
_ content: FileUploadContent,
channel: String,
remoteFilename: String,
publishRequest: PublishFileRequest = PublishFileRequest(),
custom requestConfig: RequestConfiguration = RequestConfiguration(),
uploadTask: @escaping (HTTPFileUploadTask) -> Void,
completion: ((Result<(file: PubNubLocalFile, publishedAt: Timetoken), Error>) -> Void)?
)
* required
ParameterDescription
content *
Type: FileUploadContent
Default:
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.
publishRequest
Type: PublishFileRequest
Default:
PublishFileRequest()
The request configuration object when the file is published to PubNub.
custom
Type: RequestConfiguration
Default:
RequestConfiguration
Custom configuration overrides when generating the File Upload URLRequest
uploadTask
Type: (HTTPFileUploadTask) -> Void
Default:
{ _ in }
The file upload task executing the upload; contains a reference to the actual URLSessionUploadTask.
completion
Type: ((Result<(task: HTTPFileUploadTask, file: PubNubFile, publishedAt: Timetoken), Error>) -> Void)?
Default:
n/a
The async Resultof the method call.

Details

enum FileUploadContent: CustomStringConvertible, CustomDebugStringConvertible
/// A URL to an existing file
case file(url: URL)

/// The raw content of a file and the content type that best describes it
case data(_ data: Data, contentType: String?)

/// A stream of data, the content type of that stream, and the total length of the stream in bytes
case stream(_ stream: InputStream, contentType: String?, contentLength: Int)

struct PublishFileRequest
/// The optional message that will be include alongside the File information
public var additionalMessage: JSONCodable? = nil

/// A user-provided custom message type
show all 50 lines

Basic Usage

Reference code example

This example is a self-contained code snippet ready to run in an SDK's IDE. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.

import PubNubSDK

// Creates a configuration object using the demo keys
let config = PubNubConfiguration(
publishKey: "demo",
subscribeKey: "demo",
userId: "myUniqueUserId"
)

// Initializes a PubNub object with the configuration
let pubnub = PubNub(configuration: config)

// Specify the file URL (ensure the path is correct)
let fileURL = URL(fileURLWithPath: "/path/to/cat_picture.jpg") // Replace with actual file path

show all 35 lines

Returns

The uploadTask handler will respond with an instance of HTTPFileUploadTask.

class HTTPFileUploadTask

/// The underlying URLSessionTask that is being processed
var urlSessionTask: URLSessionTask { get }

/// A representation of the overall task progress
var progress: Progress { get }

/// The background identifier of the URLSession that is processing this task
var sessionIdentifier: String? { get }

// An error object that indicates why the task failed
var error: Error? { get }

// The server's response to the currently active request
show all 19 lines

The completion handler will respond with a Result.

Success

A Tuple containing the HTTPFileUploadTaskthat completed, the PubNubFile or PubNubLocalFile that was uploaded, and the Timetoken when it was published.

protocol PubNubLocalFile

/// The local URL of the file
var fileURL: URL { get set }

/// If the local filenames change this can be used to track the remote filename
var remoteFilename: String { get }

/// The channel the file is associated with
var channel: String { get }

/// PubNub-generated ID for a file
var fileId: String { get }

/// User defined name for a file
show all 28 lines

Failure

An Error describing the failure.

List channel files

Retrieve list of files uploaded to Channel.

Method(s)

func listFiles(
channel: String,
limit: UInt = 100,
next: String? = nil,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?
)
* required
ParameterDescription
channel *
Type: String
Default:
n/a
Channel to get list of files.
limit
Type: UInt
Default:
100
Number of files to return. Minimum value is 1, and maximum is 100.
next
Type: 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.
custom
Type: RequestConfiguration
Default:
RequestConfiguration()
Custom configuration overrides when generating the File Upload URLRequest
completion
Type: ((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?
Default:
n/a
The async Result of the method call

Basic Usage

pubnub.listFiles(
channel: "my_channel"
) { result in
case let .success(response):
print("There are \(response.files.count) file(s) found")

if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
print("An error occurred while fetching the file list: \(error.localizedDescription)")
}

Returns

The completion handler will respond with a Result.

Success

A Tuple list of PubNubFile objects, and the next page identifier (if one exists).

protocol PubNubFile

/// The channel the file is associated with
var channel: String { get }

/// PubNub-generated ID for a file
var fileId: String { get }

/// User defined name for a file
var filename: String { get }

/// Size, in bytes, of the stored file
var size: Int64 { get }

/// The MIME Type of the file
show all 22 lines

Failure

An Error describing the failure.

Get File Url

Generate URL which can be used to download file from target Channel.

Method(s)

func generateFileDownloadURL(
channel: String,
fileId: String,
filename: String
) throws -> URL
* required
ParameterDescription
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.

Basic Usage

do {
let downloadURL = try pubnub.generateFileDownloadURL(channel: file.channel, fileId: file.fileId, filename: file.filename)
} catch {
print("The error the occurred generating the URL \(error.localizedDescription)")
}

Returns

The URL where the file can be downloaded.

Download file

Download file from 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)

func download(
file: PubNubFile,
toFileURL localFileURL: URL,
resumeData: Data? = nil,
downloadTask: @escaping (HTTPFileDownloadTask) -> Void,
completion: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?
)
* required
ParameterDescription
file *
Type: PubNubFile
Default:
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
resumeData
Type: Data?
Default:
nil
A data object that provides the data necessary to resume a download.
downloadTask
Type: (HTTPFileDownloadTask) -> Void
Default:
{ _ in }
The file upload task executing the upload; contains a reference to the actual URLSessionUploadTask
completion
Type: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?
Default:
n/a
The async Result of the method call.

Basic Usage

let requestFile = PubNubLocalFileBase(
fileURL: URL(fileURLWithPath: "path/to/example.png"),
channel: "my_channel",
fileId: "fileId-from-PubNub",
remoteFilename: "filename-from-PubNub"
)

pubnub.download(
file: requestFile, toFileURL: requestFile.fileURL
) { (fileTask: HTTPFileDownloadTask) in

print("The task \(fileTask.taskIdentifier) has started downloading; no need to call `resume()`")
print("If needed, the `URLSessionUploadTask` can be accessed with `fileTask.urlSessionTask`")
print("You can use `fileTask.progress` to populate a `UIProgressView`/`ProgressView` ")

show all 25 lines

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.

let resumeData = /* See above documentation on ways you can obtain this data */

let requestFile = PubNubLocalFileBase(
fileURL: URL(fileURLWithPath: "path/to/example.png"),
channel: "my_channel",
fileId: "fileId-from-PubNub",
remoteFilename: "filename-from-PubNub"
)

pubnub.download(
file: requestFile,
toFileURL: requestFile.fileURL,
resumeData: resumeData
) { (fileTask: HTTPFileDownloadTask) in

show all 29 lines

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

// Explicitly invalidate any existing tasks to avoid memory leaks when overwriting
pubnub.fileURLSession.invalidateAndCancel()

// Create and make any changes to the default configuration
// Use `URLSessionConfiguration.background(withIdentifier:)`` to create a default background configuration
let configuration = URLSessionConfiguration()

// Create the URLSession using the FileSessionManager as the delegate
pubnub.fileURLSession = URLSession(configuration: configuration, delegate: FileSessionManager(), delegateQueue: nil)

let requestFile = PubNubLocalFileBase(
fileURL: URL(fileURLWithPath: "path/to/example.png"),
channel: "my_channel",
fileId: "fileId-from-PubNub",
remoteFilename: "filename-from-PubNub"
show all 35 lines

Returns

The downloadTask handler will respond with an instance of HTTPFileUploadTask:

class HTTPFileDownloadTask

/// The underlying URLSessionTask that is being processed
var urlSessionTask: URLSessionTask { get }

/// A representation of the overall task progress
var progress: Progress { get }

/// The background identifier of the URLSession that is processing this task
var sessionIdentifier: String? { get }

/// An error object that indicates why the task failed
var error: Error? { get }

/// The server's response to the currently active request
show all 19 lines

The completion handler will respond with an instance of Result.

Success A Tuple containing the HTTPFileUploadTaskthat 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.

protocol PubNubLocalFile

/// The local URL of the file
var fileURL: URL { get set }

/// If the local filename changes this can be used to track the remote filename
var remoteFilename: String { get }

/// The channel the file is associated with
var channel: String { get }

/// PubNub-generated ID for a file
var fileId: String { get }

/// User defined name for a file
show all 28 lines

Failure An Error describing the failure.

Delete file

Delete file from specified Channel.

Method(s)

func remove(
fileId: String,
filename: String,
channel: String,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<(channel: String, fileId: String), Error>) -> Void)?
)
* required
ParameterDescription
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.
custom
Type: RequestConfiguration
Default:
RequestConfiguration()
Custom configuration overrides when generating the File Upload URLRequest
completion
Type: ((Result<(channel: String, fileId: String), Error>) -> Void)?
Default:
n/a
The async Result of the method call.

Basic Usage

self.pubnub.remove(fileId: "id-of-a-file", filename: "example.png", channel: "my_channel") { result in
case let .success(response):
print("The file whose ID is \(response.fileId) was removed from \(response.channel)")
case let .failure(error):
print("An error occurred while removing the file: \(error.localizedDescription)")
}

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.

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)

func publish(
file: PubNubFile,
request: PublishFileRequest,
completion: ((Result<Timetoken, Error>) -> Void)?
)
* required
ParameterDescription
file *
Type: PubNubFile
Default:
n/a
The PubNubFile representing the uploaded file.
publishRequest
Type: PublishFileRequest
Default:
PublishFileRequest()
The request configuration object when the file is published to PubNub.
completion
Type: ((Result<(file: PubNubLocalFile, publishedAt: Timetoken), Error>) -> Void)?
Default:
n/a
The async Result of the method call.

PublishFileRequest

* required
ParameterDescription
additionalMessage *
Type: JSONCodable?
Default:
nil
The optional message to include alongside the File information
customMessageType
Type: 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.
store
Type: Bool?
Default:
nil
If true the published message is stored in history.
ttl
Type: Int?
Default:
nil
Set a per message time to live in storage.
meta
Type: JSONCodable?
Default:
nil
Additional metadata to publish alongside the file.
customRequestConfig
Type: RequestConfiguration
Default:
RequestConfiguration?
Custom configuration overrides for this request.

Basic Usage

let file = PubNubLocalFileBase(
fileURL: URL(fileURLWithPath: "path/to/example.png"),
channel: "my_channel",
fileId: "fileId-from-PubNub"
)

pubnub.publish(
file: file,
request: publishRequest
) { result in
switch result {
case let .success(timetoken):
print("File Successfully Published at: \(timetoken)")
case let .failure(error):
print("Error publishing file: \(error.localizedDescription)")
show all 17 lines

Returns

The completion handler will respond with an instance of Result.

Success

A Timetoken of the published message.

Failure

An Error describing the failure.

Last updated on