Last active
November 3, 2023 08:44
-
-
Save mminer/3c0fbece956f3a5fa795563fafb139ae to your computer and use it in GitHub Desktop.
Displays a progress indicator on a file in the Finder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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.
@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
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