Download file from URL - Swift on macOS

Hi,

I'm creating a small app for a file download website that I run.

I currently have a UI where the user can choose, from a dropdown, a file that we have hosted, and then a download button appears. When they click Download, I want them to be presented with an NSSavePanel to choose a directory for the file - before the file starts to download.

I've tried:
Code Block Swift
let url = URL(string: "https://www.apple.com")!
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
if let localURL = localURL {
if let string = try? String(contentsOf: localURL) {
print(string)
}
}
}
task.resume()

from a Hacking With Swift tutorial but I think that's more for iOS.

When running that code, I can see the network usage of the app in Xcode go up - so it's working - but it starts straight away and there is no destination selection option.

Basically, I need a way to add a save dialog box to that snippet above.

If anyone can help I'd be hugely grateful. Thanks so much in advance!



Replies

Download tasks always download the file to a system-managed location. When they’re done, the system calls you with the URL and you can then move it into place.

How big a file are you expecting?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
The files will be between 300MB and 8GB...! Is that an issue?

Thanks for your help.

Is that an issue?

It presents you with a bit of a conundrum. Earlier I wrote:

Download tasks always download the file to a system-managed location.

If the user selects a final destination on a different volume, moving the file into place will require a copy (you can’t move across volumes). If the file is small, that copy is irrelevant. Not so for an 8 GB file.

Thus, if you allow users to download a file to an arbitrary volume, you may not want to use a download task but instead use a data task and write the incoming data to the file yourself.

This is not, alas, without its drawbacks. Probably the biggest is that you can’t use a data task in a background session, and thus there’s no way to set up the download to continue if the user quits the app.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"