-
-
Save mminer/3c0fbece956f3a5fa795563fafb139ae to your computer and use it in GitHub Desktop.
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() |
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
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
Hi I find your code but I test it in macOS 10.14, it's not work, am i missing something?