main

mattermost/focalboard

Last updated at: 29/12/2023 09:48

DownloadHandler.swift

TLDR

The DownloadHandler.swift file contains the DownloadHandler class that handles downloading files using the WKDownloadDelegate protocol. It includes two methods: download(_:decideDestinationUsing:suggestedFilename:completionHandler:) and downloadDidFinish(_:).

Methods

download(_:decideDestinationUsing:suggestedFilename:completionHandler:)

This method is called when starting a download. It allows the user to select the location of the downloaded file. The method creates a save panel and sets its properties, such as the suggested filename. After the user selects a location, the method checks if the file already exists and deletes it if necessary. Finally, it calls the completion handler with the chosen file URL.

downloadDidFinish(_:)

This method is called when a download finishes. It logs a message to the console indicating that the download has finished.

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

import Foundation
import WebKit

class DownloadHandler: NSObject, WKDownloadDelegate {
	func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
		DispatchQueue.main.async {
			// Let user select location of file
			let savePanel = NSSavePanel()
			savePanel.canCreateDirectories = true
			savePanel.nameFieldStringValue = suggestedFilename
			// BUGBUG: Specifying the allowedFileTypes causes Catalina to hang / error out
			//savePanel.allowedFileTypes = [".boardsarchive"]
			savePanel.begin { (result) in
				if result.rawValue == NSApplication.ModalResponse.OK.rawValue,
				   let fileUrl = savePanel.url {
					if (FileManager.default.fileExists(atPath: fileUrl.path)) {
						// HACKHACK: WKWebView doesn't appear to overwrite files, so delete exsiting files first
						do {
							try FileManager.default.removeItem(at: fileUrl)
						} catch {
							let alert = NSAlert()
							alert.messageText = "Unable to replace \(fileUrl.path)"
							alert.addButton(withTitle: "OK")
							alert.alertStyle = .warning
							alert.runModal()
						}
					}
					completionHandler(fileUrl)
				}
			}
		}
	}

	func downloadDidFinish(_ download: WKDownload) {
		NSLog("downloadDidFinish")
	}
}