---
source_url: https://www.pubnub.com/docs/sdks/swift/api-reference/files
title: File Sharing API for Swift Native SDK
updated_at: 2026-05-25T05:47:41.526Z
sdk_name: PubNub Swift SDK
sdk_version: 10.1.6
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# File Sharing API for Swift Native SDK

PubNub Swift SDK, use the latest version: 10.1.6

Install:

```bash
Add PubNub via Swift Package Manager or CocoaPods@10.1.6
```

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](#publish-file-message) 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.

:::warning 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](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#cryptomodule).
:::

### Method(s)

```swift
func send(
    _ content: FileUploadContent,
    channel: String,
    remoteFilename: String,
    publishRequest: PubNub.PublishFileRequest = PubNub.PublishFileRequest(),
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    uploadTask: @escaping (HTTPFileUploadTask) -> Void,
    completion: ((Result<(task: HTTPFileUploadTask, file: PubNubLocalFile, publishedAt: Timetoken), Error>) -> Void)?
)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| content | PubNub.FileUploadContent | Yes |  | The content to be uploaded. |
| channel | String | Yes |  | The channel the file should be uploaded to. |
| remoteFilename | String | Yes | `nil` | The name of the content when uploaded. |
| publishRequest | PubNub.PublishFileRequest | Optional | `PubNub.PublishFileRequest()` | The request configuration object when the file is published to PubNub. |
| custom | PubNub.RequestConfiguration | Optional | `PubNub.RequestConfiguration` | Custom configuration overrides when generating the File Upload `URLRequest`. |
| uploadTask | (HTTPFileUploadTask) | Optional | `{ _ in }` | The file upload task executing the upload; contains a reference to the actual `URLSessionUploadTask`. |
| completion | ((Result<(task: | Optional |  | The async `Result`of the method call. |

#### Details

```swift
/// Content that can be uploaded as a File to PubNub
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)
}

/// Additional information that can be sent during a File publish
struct PublishFileRequest {

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

  /// A user-provided custom message type
  public var customMessageType: String?

  /// A user-provided custom message type. If true the published message is stored in history.
  public var store: Bool?

  /// Set a per message time to live in storage.
  public var ttl: Int?

  /// Additional metadata to publish alongside the file
  public var meta: JSONCodable?

  /// Custom configuration overrides for this request
  public var customRequestConfig: RequestConfiguration
}

/// 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
  var response: HTTPURLResponse? { get }

  // The body of the response
  var responseData: Data? { get }
}
```

### 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.

```swift
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
  var filename: String { get }

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

  /// The MIME Type of the file
  var contentType: String { get }

  /// ISO 8601 date and time the file was uploaded
  var createdDate: Date? { get set }

  /// Custom payload that can be used to store additional file details
  var custom: JSONCodable? { get set }
}
```

#### Failure

An `Error` describing the failure.

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```swift
import PubNubSDK
import Foundation

// Initializes a PubNub object with the configuration
let pubnub = PubNub(
  configuration: PubNubConfiguration(
    publishKey: "demo",
    subscribeKey: "demo",
    userId: "myUniqueUserId"
  )
)

// Sends a File to a channel
pubnub.send(
  .file(url: URL(fileURLWithPath: "/path/to/your/file.jpg")),
  channel: "my_channel",
  remoteFilename: "cat_picture.jpg",
  publishRequest: .init(additionalMessage: ["text": "Look at this photo!"], customMessageType: "yourCustomMessageType")
) { (fileTask: HTTPFileUploadTask) in
  print("The task \(fileTask.urlSessionTask.taskIdentifier) has started uploading; 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`")
} completion: { result in
  switch result {
  case let .success((task, file, publishedAt)):
    print("The file with an ID of \(file.fileId) was uploaded at \(publishedAt) timetoken)")
  case let .failure(error):
    print("An error occurred while uploading the file: \(error.localizedDescription)")
  }
}
```

### Other examples

#### Send file with push notification

:::tip 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.
:::

```swift
let pushPayload = PubNubPushMessage(
apns: PubNubAPNSPayload(
  aps: APSPayload(alert: .object(.init(title: "New File", body: "A file was shared"))),
  pubnub: [.init(targets: [.init(topic: "com.yourapp.bundleid", environment: .production)])],
  payload: ["text": "Check out this file!"]
),
fcm: PubNubFCMPayload(
  payload: ["text": "Check out this file!"],
  target: nil,
  notification: FCMNotificationPayload(title: "New File", body: "A file was shared")
)
)

pubnub.send(
.file(url: fileURL),
channel: "my-channel",
remoteFilename: "example.txt",
publishRequest: PubNub.PublishFileRequest(additionalMessage: pushPayload)
) { result in
// Handle result
}
```

For more details on push notification payload structure, see the [iOS Push](https://www.pubnub.com/docs/general/push/ios) and [Android Push](https://www.pubnub.com/docs/general/push/android) 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)

```swift
func listFiles(
    channel: String,
    limit: UInt = 100,
    next: String? = nil,
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    completion: ((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: 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: `PubNub.RequestConfiguration`Default: `PubNub.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. |

### Returns

The `completion` handler will respond with a `Result`.

#### Success

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

```swift
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
  var contentType: String { get }

  /// ISO 8601 date and time the file was uploaded
  var createdDate: Date? { get set }

  /// Custom payload that can be used to store additional file details
  var custom: JSONCodable? { get set }
}
```

#### Failure

An `Error` describing the failure.

### Sample code

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

## Get file URL

Generate a URL to download a file from the target `channel`.

### Method(s)

```swift
func generateFileDownloadURL(
    channel: String,
    fileId: String,
    filename: String
) 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

```swift
// Generate a download URL for a File
let downloadURL = try? pubnub.generateFileDownloadURL(
  channel: "some-channel",
  fileId: "some-file-id",
  filename: "filename"
)
```

## Download file

Download a file from the specified `channel`.

:::warning File encryption
If the `cryptoModule` is set in PubNub config, it will be used for decryption. For more information, refer to [Crypto module configuration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#cryptomodule).
:::

### Method(s)

```swift
func download(
    file: PubNubFile,
    toFileURL localFileURL: URL,
    resumeData: Data? = nil,
    downloadTask: @escaping (HTTPFileDownloadTask) -> Void,
    completion: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?
)
```

| Parameter | Description |
| --- | --- |
| `file` *Type: `PubNubFile`Default: n/a | The file that should be downloaded. |
| `toFileURL` *Type: URLDefault: 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 `URLSessionDownloadTask`. |
| `completion`Type: `((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 `HTTPFileDownloadTask`that 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.

```swift
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
  var response: HTTPURLResponse? { get

  /// The location where the temporary downloaded file should be copied
  var destinationURL: URL { get }
}
```

```swift
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
  var filename: String { get }

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

  /// The MIME Type of the file
  var contentType: String { get }

  /// ISO 8601 date and time the file was uploaded
  var createdDate: Date? { get set }

  /// Custom payload that can be used to store additional file details
  var custom: JSONCodable? { get set }
}
```

#### Failure

An `Error` describing the failure.

### Sample code

```swift
// Replace `fileURL:` with your destination URL
let requestFile = PubNubLocalFileBase(
  channel: "my_channel",
  fileId: "fileId-from-PubNub",
  fileURL: URL(fileURLWithPath: "your/download/url.png")
)

// Download the File to the specified URL
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`")
} completion: { result in
  switch result {
  case let .success((task, newFile)):
    print("The file task \(task.taskIdentifier) downloaded successfully to \(newFile.fileURL), which might be different than \(requestFile.fileURL)")
    print("This also might mean that \(newFile.filename) could be different from \(newFile.remoteFilename)")
  case let .failure(error):
    print("An error occurred while downloading the file: \(error.localizedDescription)")
  }
}
```

#### Resume download

Downloads can be paused and resumed at a later time under certain conditions. See [Pausing and Resuming Downloads](https://developer.apple.com/documentation/foundation/url_loading_system/pausing_and_resuming_downloads?language=objc) and [cancel(byProducingResumeData:)](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel)

If you were given `resumeData` you can use the following example to try and resume your download; otherwise you can restart a new download.

```swift
// Assumes this is the portion of the File that was downloaded prior to the interruption.
// See above documentation on how to obtain this data
let resumeData = Data()

// Replace `fileURL:` with your destination URL
let fileToResume = PubNubLocalFileBase(
  channel: "my_channel",
  fileId: "fileId-from-PubNub",
  fileURL: URL(fileURLWithPath: "your/download/url.png")
)

// Resume the download of the File
pubnub.download(
  file: fileToResume,
  toFileURL: fileToResume.fileURL,
  resumeData: resumeData
) { (fileTask: HTTPFileDownloadTask) in
  print("The task \(fileTask.urlSessionTask.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`")
} completion: { result in
  switch result {
  case let .success((task, newFile)):
    print("The file task \(task.taskIdentifier) downloaded successfully to \(newFile.fileURL), which might be different than \(fileToResume.fileURL)")
    print("This also might mean that \(newFile.filename) could be different from \(newFile.remoteFilename)")
  case let .failure(error):
    print("An error occurred while downloading the file: \(error.localizedDescription)")
  }
}
```

#### Custom URLSession

By default, the PubNub instance will use a [background](https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1407496-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](https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background)

```swift
// Initialize a PubNub object with a custom URL session
let pubNubWithCustomFileURLSession = PubNub(
  configuration: PubNubConfiguration(
    publishKey: "demo",
    subscribeKey: "demo",
    userId: "myUniqueUserId"
  ),
  fileSession: URLSession(
    configuration: .init(),
    delegate: FileSessionManager(),
    delegateQueue: nil
  )
)

// Replace `fileURL:` with your destination URL
let fileToDownload = PubNubLocalFileBase(
  channel: "my_channel",
  fileId: "fileId-from-PubNub",
  fileURL: URL(fileURLWithPath: "your/download/url.png")
)

// Download the File using a PubNub instance with a custom file session
pubNubWithCustomFileURLSession.download(
  file: fileToDownload,
  toFileURL: fileToDownload.fileURL
) { (fileTask: HTTPFileDownloadTask) in
  print("The task \(fileTask.urlSessionTask.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` ")
} completion: { result in
  switch result {
  case let .success((task, newFile)):
    print("The file task \(task.taskIdentifier) downloaded successfully to \(newFile.fileURL), which might be different than \(fileToDownload.fileURL)")
    print("This also might mean that \(newFile.filename) could be different from \(newFile.remoteFilename)")
  case let .failure(error):
    print("An error occurred while downloading the file: \(error.localizedDescription)")
  }
}
```

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```swift
func remove(
    fileId: String,
    filename: String,
    channel: String,
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    completion: ((Result<(channel: String, fileId: String), Error>) -> Void)?
)
```

| Parameter | Description |
| --- | --- |
| `fileId` *Type: StringDefault: n/a | Unique file identifier which has been assigned during file upload. |
| `filename` *Type: StringDefault: n/a | Name under which the uploaded file is stored. |
| `channel` *Type: StringDefault: n/a | 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: 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 `channel`that completed and the `fileId` of the removed file.

#### Failure

An `Error` describing the failure.

### Sample code

```swift
// Remove a File from a channel
pubnub.remove(
  fileId: "id-of-a-file",
  filename: "example.png",
  channel: "my_channel"
) { result in
  switch result {
  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)")
  }
}
```

## Publish file message

Publish the uploaded file message to a specified channel.

This method is called internally by [send](#send-file) 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)

```swift
func publish(
    file: PubNubFile,
    request: PublishFileRequest,
    completion: ((Result<Timetoken, Error>) -> Void)?
)
```

| Parameter | Description |
| --- | --- |
| `file` *Type: `PubNubFile`Default: n/a | The `PubNubFile` representing the uploaded file. |
| `request` *Type: `PubNub.PublishFileRequest`Default: n/a | Additional information that can be sent during a File publish. |
| `completion`Type: `((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. |
| `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: `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

```swift
// Assume this is a File that you want to publish to a channel
let someFile = PubNubLocalFileBase(
  channel: "my_channel",
  fileId: "fileId-from-PubNub",
  fileURL: URL(fileURLWithPath: "path/to/example.png")
)

// Provides additional message that can be send during a File publish
let publishRequest = PubNub.PublishFileRequest(
  additionalMessage: "Some additional message",
  customMessageType: "customMessageType"
)

// Publish the File to a channel
pubnub.publish(
  file: someFile,
  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)")
  }
}
```