Skip to main content

Overview

The FilesHandler protocol provides methods for downloading files from Salesforce records. Use this handler to retrieve files associated with ContentDocument records in your Salesforce instance.

Protocol Definition

public protocol FilesHandler: Sendable {
    func download(recordId: String) async throws -> FileDownloadResponse
}

Implementation

SalesforceFilesHandler

The SDK provides SalesforceFilesHandler as the default implementation of the FilesHandler protocol.
public struct SalesforceFilesHandler: FilesHandler {
    public init(
        salesforceClient: SalesforceClient,
        accessToken: String,
        instanceUrl: String
    )
}

Parameters

salesforceClient
SalesforceClient
required
The Salesforce client instance used for API requests
accessToken
String
required
The OAuth access token for authenticating with Salesforce
instanceUrl
String
required
The Salesforce instance URL (e.g., “https://your-instance.salesforce.com”)

Methods

download

Downloads a file from Salesforce using a record ID.
func download(recordId: String) async throws -> FileDownloadResponse

Parameters

recordId
String
required
The Salesforce record ID to download the file from. Must be a valid 15 or 18 character Salesforce ID.

Returns

Returns a FileDownloadResponse containing the file data and metadata.

Throws

Throws FileDownloadError if the download fails. See Error Handling for details.

Usage Example

Basic File Download

import CongregationKit

let congregation = try await CongregationKit(
    httpClient: httpClient,
    credentials: credentials
)

// Download a file by record ID
let response = try await congregation.files.download(
    recordId: "a0x2w000002jxqn"
)

print("Downloaded: \(response.fullFilename)")
print("Size: \(response.fileSize) bytes")
print("Type: \(response.contentType)")

// Access the file data
let fileData = response.data

Save Downloaded File to Disk

import Foundation

let response = try await congregation.files.download(
    recordId: "a0x2w000002jxqn"
)

let fileURL = URL(fileURLWithPath: "/path/to/save/\(response.fullFilename)")
try response.data.write(to: fileURL)

print("File saved to: \(fileURL.path)")

Handle Different File Types

let response = try await congregation.files.download(
    recordId: recordId
)

switch response.fileExtension {
case "pdf":
    // Handle PDF file
    processPDF(response.data)
case "jpg", "jpeg", "png":
    // Handle image file
    processImage(response.data)
case "docx", "doc":
    // Handle document file
    processDocument(response.data)
default:
    // Handle other file types
    print("Unknown file type: \(response.fileExtension)")
}

Error Handling

The download method throws FileDownloadError when operations fail:
do {
    let response = try await congregation.files.download(
        recordId: "invalid_id"
    )
    // Process file
} catch FileDownloadError.fileNotFound {
    print("File not found for the given record ID")
} catch FileDownloadError.invalidRecordId {
    print("Invalid record ID format")
} catch FileDownloadError.noFilesAssociated {
    print("No files are associated with this record")
} catch FileDownloadError.contentVersionNotFound {
    print("File content version not found")
} catch FileDownloadError.invalidFileData {
    print("Invalid file data received")
} catch FileDownloadError.networkError(let error) {
    print("Network error: \(error.localizedDescription)")
} catch FileDownloadError.serverError(let message) {
    print("Server error: \(message)")
} catch FileDownloadError.downloadFailed(let error) {
    print("Download failed: \(error.localizedDescription)")
} catch {
    print("Unexpected error: \(error)")
}

FileDownloadError Cases

fileNotFound
FileDownloadError
The requested file was not found for the given record ID
invalidRecordId
FileDownloadError
The record ID format is invalid (must be 15-18 alphanumeric characters)
invalidFileData
FileDownloadError
The file data received is corrupted or invalid
downloadFailed
FileDownloadError
The API request to download the file failed
noFilesAssociated
FileDownloadError
No files are associated with the given record ID
contentVersionNotFound
FileDownloadError
The file content version could not be found in Salesforce
networkError
FileDownloadError
Network error occurred during file download
serverError
FileDownloadError
Server error from Salesforce with error message

Best Practices

Record ID Validation: Salesforce record IDs must be 15 or 18 characters long and contain only alphanumeric characters. The SDK automatically validates record IDs before making API requests.
Large Files: For large file downloads, consider implementing progress tracking and handling potential timeout scenarios. The SDK uses async/await, which allows you to implement cancellation if needed.
Memory Usage: File data is loaded entirely into memory as Data. For very large files, consider streaming the data to disk incrementally to avoid memory issues.

See Also

Build docs developers (and LLMs) love