Files API for PubNub Swift Native SDK
Note
The PubNub Swift 3.0 SDK contains many significant changes from the 2.x SDK, including breaking changes. Please refer to the PubNub Swift 3.0 Migration Guide for more details.
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
Description
Upload file / data to specified channel
.
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)? )
Parameter Type Required Default Description content
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
PublishFileRequest
Optional PublishFileRequest()
The request configuration object when the file is published to PubNub. custom
RequestConfiguration
Optional RequestConfiguration
Custom configuration overrides when generating the File Upload URLRequest
uploadTask
(HTTPFileUploadTask) -> Void
Optional { _ in }
The file upload task executing the upload; contains a reference to the actual URLSessionUploadTask
.completion
((Result<(task: HTTPFileUploadTask, file: PubNubFile, publishedAt: Timetoken), Error>) -> Void)?
Optional The async Result
of 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 /// If true the published message is stored in history. public var store: Bool? = nil /// Set a per message time to live in storage. public var ttl: Int? = nil /// Additional metadata to publish alongside the file public var meta: JSONCodable? = nil /// Custom configuration overrides for this request public var customRequestConfig: RequestConfiguration = 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 }
Basic Usage
let fileURL = URL(fileURLWithPath: "path/to/example.png")
pubnub.send(
.file(url: fileURL),
channel: "my_channel",
remoteFilename: fileURL.lastPathComponent
) { (fileTask: HTTPFileUploadTask) in
print("The task \(fileTask.task.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((newFile, publishedAt)):
print("The file with an ID of \(newFile.fileId) was uploaded at \(publishedAt) timetoken) ")
case let .failure(error):
print("An error occurred while uploading the file: \(error.localizedDescription)")
}
}
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
var response: HTTPURLResponse? { get
// The body of the response
var responseData: Data? { get }
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.
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.
List channel files
Description
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)? )
Parameter Type Required Default Description channel
String Yes Channel to get list of files. limit
UInt
Optional 100 Number of files to return. Minimum value is 1, and maximum is 100. next
String? Optional nil
Previously-returned cursor bookmark for fetching the next page. custom
RequestConfiguration
Optional RequestConfiguration()
Custom configuration overrides when generating the File Upload URLRequest
completion
((Result<(files: [PubNubFile], next: String?), Error>) -> Void)?
Optional 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
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.
Get File Url
Description
Generate URL which can be used to download file from target Channel
.
Method(s)
func generateFileDownloadURL( channel: String, fileId: String, filename: String ) throws -> URL
Parameter Type Required Description channel
String Yes Name of channel
to which the file has been uploaded.fileID
String Yes Unique file identifier which has been assigned during file upload filename
String Yes 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
Description
Download file from specified Channel
.
Method(s)
func download( file: PubNubFile, toFileURL localFileURL: URL, resumeData: Data? = nil, downloadTask: @escaping (HTTPFileDownloadTask) -> Void, completion: ((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)? )
Parameter Type Required Default Description file
PubNubFile
Yes The file that should be downloaded. toFileURL
URL Yes The file URL where the file should be downloaded to. This is NOT the URL returned from generateFileDownloadURL
resumeData
Data?
Optional nil
A data object that provides the data necessary to resume a download. downloadTask
(HTTPFileDownloadTask) -> Void
Optional { _ in }
The file upload task executing the upload; contains a reference to the actual URLSessionUploadTask
completion
((Result<(task: HTTPFileDownloadTask, file: PubNubLocalFile), Error>) -> Void)?
Optional 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` ")
} 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 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
print("The task \(fileTask.task.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: { [weak self] 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)")
}
}
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"
)
pubnub.download(
file: requestFile, toFileURL: requestFile.fileURL
) { (fileTask: HTTPFileDownloadTask) in
print("The task \(fileTask.task.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)")
}
}
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
var response: HTTPURLResponse? { get
/// The location where the temporary downloaded file should be copied
var destinationURL: URL { get }
The completion
handler will respond with an instance of Result
:
Success A Tuple
containing the HTTPFileUploadTask
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.
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.
Delete file
Description
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)? )
Parameter Type Required Default Description fileId
String Yes Unique file identifier which has been assigned during file upload filename
String Yes Name under which the uploaded file is stored. channel
String Yes Channel the file was sent to. custom
RequestConfiguration
Optional RequestConfiguration()
Custom configuration overrides when generating the File Upload URLRequest
completion
((Result<(channel: String, fileId: String), Error>) -> Void)?
Optional 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 channel
that completed and the fileId
of the removed file.
Failure An Error
describing the failure.
Publish file message
Description
Publish file message from specified Channel
.
Method(s)
func publish( file: PubNubFile, request: PublishFileRequest, completion: ((Result<Timetoken, Error>) -> Void)? )
Parameter Type Required Default Description file
PubNubFile
Yes The PubNubFile
representing the uploaded file.publishRequest
PublishFileRequest
Optional PublishFileRequest()
The request configuration object when the file is published to PubNub. completion
((Result<(file: PubNubLocalFile, publishedAt: Timetoken), Error>) -> Void)?
Optional The async Result
of the method call.PublishFileRequest
Parameter Type Required Default Description additionalMessage
JSONCodable?
Yes nil
The optional message to include alongside the File information store
Bool?
Optional nil
If true the published message is stored in history. ttl
Int?
Optional nil
Set a per message time to live in storage. meta
JSONCodable?
Optional nil
Additional metadata to publish alongside the file. customRequestConfig
RequestConfiguration
Optional 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)")
}
}
Returns
The completion
handler will respond with an instance of Result
:
Success A Timetoken
of the published message.
Failure An Error
describing the failure.