Skip to content
CefSwift
Esc
↑↓navigate↵open⌘Jpreview
On this page

Downloads

Where downloads go, deciding per download, and the observable download list; file choosers.

profile.downloadPolicy = .ask   // .downloadsFolder (the default), .folder(url), .ask, .disabled
for download in profile.downloads {
    print(download.suggestedFilename, download.fractionCompleted)
}

Gallery: DownloadsDemo. Browser example: Features/Downloads lists downloads from a toolbar button.

Downloads

Downloads belong to the profile, as Chromium keeps them. A download goes where its profile’s downloadPolicy says, unless the profile’s delegate decides otherwise. The policy is a setting an app, or its settings window, sets without writing a delegate:

profile.downloadPolicy = .ask   // .downloadsFolder (the default), .folder(url), .ask, .disabled
Policy Effect
.downloadsFolder Saves in the user’s Downloads folder under the suggested name, numbered (report (1).pdf) when the name is taken. The default.
.folder(url) The same, in url.
.ask Shows a save panel for each download, as a sheet on the page’s window, proposing the suggested name and type. Cancel cancels the download.
.disabled Cancels every download.

The default is the Downloads folder, as in Safari and Chrome: a download the user started should arrive without a question, and a panel that opens on its own would stall an app nobody is watching. WKWebView has no default and makes its delegate choose; CefSwift’s delegate methods all have one, and this is it.

To decide per download, implement CefProfileDelegate.profile(_:decideDestinationFor:). Its answer wins over the policy; CefDownloadDecision.default(for:) is what the policy would do. The download’s page is the page that started it:

final class Downloads: CefProfileDelegate {
    func profile(_ profile: CefProfile, decideDestinationFor download: CefDownload) async -> CefDownloadDecision {
        if download.mimeType == "application/pdf" { return .ask }
        guard download.url?.host() != "ads.example" else { return .cancel }
        return .default(for: download)
    }
}

.save(to: file) saves as exactly that file, .saveInFolder(folder) under the suggested name, numbered when taken, .ask shows the save panel and .cancel cancels. To show a panel of your own, show it and return .save(to:) with the user’s choice, or .cancel. CefDownloadPresenter is the stock panel, for a delegate that keeps it for some downloads.

Each download is one observable CefDownload for its whole life, updated as it goes: url (after redirects; originalURL before), startDate, endDate (once completed or cancelled), suggestedFilename, mimeType, fileURL (the file being written, then the finished file), receivedBytes, expectedBytes (nil when the server gives no size), fractionCompleted, bytesPerSecond, estimatedTimeRemaining, the page that started it, and a state: .inProgress, .paused, .completed, .cancelled, or .interrupted(reason) when an error stopped it. pause(), resume() and cancel() control it while the page that started it is open; a paused or interrupted download keeps its controls, so one that canResume continues with resume(). page.startDownload(_:) starts one.

page.downloads lists a page’s downloads, oldest first, and profile.downloads those of every page of the profile, so a download manager reads one list instead of being every page’s delegate:

struct DownloadsList: View {
    let profile: CefProfile

    var body: some View {
        List(profile.downloads.reversed()) { download in
            HStack {
                Text(download.fileURL?.lastPathComponent ?? download.suggestedFilename)
                if download.state == .inProgress {
                    ProgressView(value: download.fractionCompleted ?? 0)
                    Button("Cancel", systemImage: "xmark.circle", action: download.cancel)
                }
            }
        }
    }
}

The lists last as long as the app runs, an incognito profile’s as long as the profile. CefSwift keeps no download history across launches; an app that wants one saves what it needs from profile.downloads. profile.removeDownloads(where:) takes entries out of the profile’s list and their pages’, and profile.removeFinishedDownloads() takes out every one that cannot go on any more, as a download manager’s Clear does; a download that can still go on (in progress, or paused or interrupted while its page is open) stays, and no file is deleted.

Code that does not use SwiftUI follows a download with Observation’s withObservationTracking(_:onChange:), or by reading the lists when it needs them; there is no delegate event for download progress.

File choosers

An <input type="file"> or showOpenFilePicker() asks the delegate, with a CefFileDialog: its mode (.open, .openMultiple, .openFolder, .save), the page’s title, a defaultURL, and the acceptedTypes the page lists, each with its contentTypes as UTTypes. Return the chosen files, or nil to cancel:

func page(_ page: CefPage, runFileDialog dialog: CefFileDialog) async -> [URL]? {
    if dialog.mode == .open, let recent = recentDocument { return [recent] }
    return await CefFileDialogPresenter.present(dialog, in: page.hostWindow)
}

The default, CefFileDialogPresenter, shows an NSOpenPanel (or NSSavePanel) as a sheet on the page’s window, limited to the accepted types. A page that navigates away closes the panel as Cancel. CefSwift has no API for opening a file panel on the app’s behalf: use NSOpenPanel.

Was this page helpful?