Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active November 3, 2023 08:44
Show Gist options
  • Save mminer/3c0fbece956f3a5fa795563fafb139ae to your computer and use it in GitHub Desktop.
Save mminer/3c0fbece956f3a5fa795563fafb139ae to your computer and use it in GitHub Desktop.
Displays a progress indicator on a file in the Finder.
import Foundation
let progress = Progress(parent: nil, userInfo: [
.fileOperationKindKey: Progress.FileOperationKind.downloading,
.fileURLKey: URL(fileURLWithPath: "/Users/mminer/Downloads/somefile.zip"),
])
progress.isCancellable = true
progress.isPausable = false
progress.kind = .file
progress.totalUnitCount = 10
progress.publish()
// Simulate downloading a file.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { progress.completedUnitCount = 1 }
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { progress.completedUnitCount = 2 }
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { progress.completedUnitCount = 3 }
DispatchQueue.main.asyncAfter(deadline: .now() + 4) { progress.completedUnitCount = 4 }
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { progress.completedUnitCount = 5 }
RunLoop.current.run()
@dinneo
Copy link

dinneo commented Jun 5, 2019

Hi I find your code but I test it in macOS 10.14, it's not work, am i missing something?

@amomchilov
Copy link

If you just run this as a standalone Swift file (which seems to be what's intended, given the formatting), then this won't work. As soon as the async tasks are registered, the program completes and exits, without the async tasks ever firing. You need a mechanism to keep the program alive until the tasks are finished, and that's precisely what a RunLoop can do.

See my fork: https://gist.github.com/amomchilov/7a977b9f99e898f0ff5d8e500c213aef

@mminer
Copy link
Author

mminer commented Jun 5, 2019

It's been a while since I wrote this code, but I believe it's a snippet from a larger program and wasn't intended as a standalone script. Sorry for the confusion. Using a RunLoop looks like the right approach.

@mminer
Copy link
Author

mminer commented Jun 13, 2019

@dinneo: I updated the snippet with @amomchilov's suggestion and it should run fine now from the command line (provided you substitute the file path on line 5 with one that exists on your own machine).

swift DownloadProgressIndicatorDemo.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment