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)
required
content required#
Type: PubNub.FileUploadContent
Default: no default
The content to be uploaded.
channel required#
Type: String
Default: no default
The channel the file should be uploaded to.
remoteFilename required#
Type: String
Default: nil
The name of the content when uploaded.
publishRequest#
Type: PubNub.PublishFileRequest
Default: PubNub.PublishFileRequest()
The request configuration object when the file is published to PubNub.
custom#
Type: PubNub.RequestConfiguration
Default: PubNub.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: no default
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 lines

Returns​

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 lines

Failure​

An Error describing the failure.

Sample code​

1import PubNubSDK
2import Foundation
3
4// Initializes a PubNub object with the configuration
5let pubnub = PubNub(
6 configuration: PubNubConfiguration(
7 publishKey: "demo",
8 subscribeKey: "demo",
9 userId: "myUniqueUserId"
10 )
11)
12
13// Sends a File to a channel
14pubnub.send(
15 .file(url: URL(fileURLWithPath: "/path/to/your/file.jpg")),
show all 30 lines

Other examples​

Send file with push notification​

Trigger push notifications when sharing files

To send mobile push notifications when sharing a file, include pn_apns (for iOS) and/or pn_fcm (for Android) payloads in the message parameter of the send method.

When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.

1let pushPayload = PubNubPushMessage(
2apns: PubNubAPNSPayload(
3 aps: APSPayload(alert: .object(.init(title: "New File", body: "A file was shared"))),
4 pubnub: [.init(targets: [.init(topic: "com.yourapp.bundleid", environment: .production)])],
5 payload: ["text": "Check out this file!"]
6),
7fcm: PubNubFCMPayload(
8 payload: ["text": "Check out this file!"],
9 target: nil,
10 notification: FCMNotificationPayload(title: "New File", body: "A file was shared")
11)
12)
13
14pubnub.send(
15.file(url: fileURL),
show all 21 lines

For more details on push notification payload structure, see the iOS Push and Android Push documentation. To prevent the sender from receiving their own push notification, add their device token to excluded_devices in the pn_push targets.

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)
required
channel required#
Type: String
Default: no default
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: PubNub.RequestConfiguration
Default: PubNub.RequestConfiguration()
Custom configuration overrides when generating the File Upload URLRequest.
completion#
Type: ((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?
Default: no default
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 lines

Failure​

An Error describing the failure.

Sample code​

1// Retrieve list of files uploaded to a channel
2pubnub.listFiles(channel: "my_channel") { result in
3 switch result {
4 case let .success(response):
5 print("There are \(response.files.count) file(s) found")
6 print("The next page used for pagination: \(String(describing: response.next))")
7 case let .failure(error):
8 print("An error occurred while fetching the file list: \(error.localizedDescription)")
9 }
10}

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
required
channel required#
Type: String
Name of channel to which the file has been uploaded.
fileID required#
Type: String
Unique file identifier which has been assigned during file upload.
filename required#
Type: String
Name under which the uploaded file is stored.

Returns​

The URL where the file can be downloaded.

Sample code​

1// Generate a download URL for a File
2let downloadURL = try? pubnub.generateFileDownloadURL(
3 channel: "some-channel",
4 fileId: "some-file-id",
5 filename: "filename"
6)

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)
required
file required#
Type: PubNubFile
Default: no default
The file that should be downloaded.
toFileURL required#
Type: URL
Default: no default
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 URLSessionDownloadTask.
completion#
Type: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?
Default: no default
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 lines
1protocol 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 lines

Failure​

An Error describing the failure.

Sample code​

1// Replace `fileURL:` with your destination URL
2let requestFile = PubNubLocalFileBase(
3 channel: "my_channel",
4 fileId: "fileId-from-PubNub",
5 fileURL: URL(fileURLWithPath: "your/download/url.png")
6)
7
8// Download the File to the specified URL
9pubnub.download(
10 file: requestFile,
11 toFileURL: requestFile.fileURL
12) { (fileTask: HTTPFileDownloadTask) in
13 print("The task \(fileTask.taskIdentifier) has started downloading; no need to call `resume()`")
14 print("If needed, the `URLSessionUploadTask` can be accessed with `fileTask.urlSessionTask`")
15 print("You can use `fileTask.progress` to populate a `UIProgressView`/`ProgressView`")
show all 24 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.

1// Assumes this is the portion of the File that was downloaded prior to the interruption.
2// See above documentation on how to obtain this data
3let resumeData = Data()
4
5// Replace `fileURL:` with your destination URL
6let fileToResume = PubNubLocalFileBase(
7 channel: "my_channel",
8 fileId: "fileId-from-PubNub",
9 fileURL: URL(fileURLWithPath: "your/download/url.png")
10)
11
12// Resume the download of the File
13pubnub.download(
14 file: fileToResume,
15 toFileURL: fileToResume.fileURL,
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

1// Initialize a PubNub object with a custom URL session
2let pubNubWithCustomFileURLSession = PubNub(
3 configuration: PubNubConfiguration(
4 publishKey: "demo",
5 subscribeKey: "demo",
6 userId: "myUniqueUserId"
7 ),
8 fileSession: URLSession(
9 configuration: .init(),
10 delegate: FileSessionManager(),
11 delegateQueue: nil
12 )
13)
14
15// Replace `fileURL:` with your destination URL
show all 38 lines

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)
required
fileId required#
Type: String
Default: no default
Unique file identifier which has been assigned during file upload.
filename required#
Type: String
Default: no default
Name under which the uploaded file is stored.
channel required#
Type: String
Default: no default
Channel the file was sent to.
custom#
Type: PubNub.RequestConfiguration
Default: PubNub.RequestConfiguration()
Custom configuration overrides when generating the File Download URLRequest.
completion#
Type: ((Result<(channel: String, fileId: String), Error>) -> Void)?
Default: no default
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// Remove a File from a channel
2pubnub.remove(
3 fileId: "id-of-a-file",
4 filename: "example.png",
5 channel: "my_channel"
6) { result in
7 switch result {
8 case let .success(response):
9 print("The file whose ID is \(response.fileId) was removed from \(response.channel)")
10 case let .failure(error):
11 print("An error occurred while removing the file: \(error.localizedDescription)")
12 }
13}

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)
required
file required#
Type: PubNubFile
Default: no default
The PubNubFile representing the uploaded file.
request required#
Type: PubNub.PublishFileRequest
Default: no default
Additional information that can be sent during a File publish.
completion#
Type: ((Result<Timetoken, Error>) -> Void)?
Default: no default
The async Result of the method call.

PubNub.PublishFileRequest​

required
additionalMessage required#
Type: JSONCodable?
Default: nil
The optional message to include alongside the File information.
customMessageType#
Type: String?
Default: no default
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: PubNub.RequestConfiguration
Default: 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// Assume this is a File that you want to publish to a channel
2let someFile = PubNubLocalFileBase(
3 channel: "my_channel",
4 fileId: "fileId-from-PubNub",
5 fileURL: URL(fileURLWithPath: "path/to/example.png")
6)
7
8// Provides additional message that can be send during a File publish
9let publishRequest = PubNub.PublishFileRequest(
10 additionalMessage: "Some additional message",
11 customMessageType: "customMessageType"
12)
13
14// Publish the File to a channel
15pubnub.publish(
show all 25 lines

Was this page useful?

Last updated on