Skip to main content

Overview

R2UploadService handles file uploads to Cloudflare R2 storage using the S3-compatible API with AWS Signature V4 authentication. The service provides progress tracking and connection testing capabilities.
Located at: Fiaxe/Services/R2UploadService.swift:5

Type Definition

Implemented as a nonisolated enum to allow calling from any actor context without isolation restrictions.

Methods

upload()

Uploads a file to R2 via a signed PUT request with progress tracking.
URL
required
Security-scoped URL of the file to upload. Must be accessible with proper permissions.
R2Credentials
required
R2 credentials containing:
  • Account ID
  • Bucket name
  • Access key ID
  • Secret access key
  • Endpoint URL
String
required
Object key in the bucket (e.g., "abc12345-photo.jpg"). This becomes the file’s path in R2.
String
required
MIME type of the file (e.g., "image/jpeg", "application/pdf"). Used to set the Content-Type header.
@MainActor @escaping @Sendable (Int64, Int64) -> Void
required
Progress callback fired on the main actor with (bytesSent, totalBytes). Called periodically during upload to report progress.
Returns: UploadResult containing the HTTP status code and response body. Throws: URLError or network-related errors if the upload fails.

Implementation Details

The upload process:
  1. Constructs the full R2 endpoint URL: {endpoint}/{bucketName}/{key}
  2. Creates a PUT request with Content-Type and Content-Length headers
  3. Signs the request using AWS Signature V4 with UNSIGNED-PAYLOAD (for streaming uploads)
  4. Uses a custom URLSessionTaskDelegate to track upload progress
  5. Returns status code and response body upon completion

testConnection()

Performs a HEAD request to verify connectivity and credentials.
R2Credentials
required
R2 credentials to test. The method verifies access to the specified bucket.
Returns: true if the connection succeeds (HTTP 200), false otherwise. Throws: Network errors if the request fails.

Implementation Details

The method sends a HEAD request to the bucket root to verify:
  • Credentials are valid
  • Bucket is accessible
  • Network connectivity is working

Data Types

UploadResult

Result structure returned from successful uploads.
Int
HTTP status code from the R2 response. Typically 200 for successful uploads.
Data
Raw response body data from the server. Usually contains XML response with upload details.

Progress Tracking

The service uses a private UploadProgressDelegate class that implements URLSessionTaskDelegate to track upload progress:
Progress updates are automatically dispatched to the main actor for UI updates.

Usage Example