Created
March 1, 2021 10:50
-
-
Save akovalov/7b22735e1fb7f1117bf04659e214d785 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// DownloadProgress.swift | |
// | |
import Foundation | |
class DownloadProgress { | |
// MARK: - Properties | |
var estimatedTimeRemaining: TimeInterval? | |
var onEstimatedTimeRemainingUpdate: ((_ time: TimeInterval?) -> Void)? | |
private(set) var progress: Progress? | |
private var remainingTimeTimer: Timer? | |
private let smoothingFactor: Double = 0.05 | |
private var averageSpeed: Double = 0 | |
private var lastSpeed: Int64 = 0 | |
private var lastCompletedUnitCount: Int64 = 0 | |
// MARK: - Lifecycle | |
init() { | |
startRemainingTimeTimer() | |
} | |
deinit { | |
stopRemainingTimeTimer() | |
} | |
// MARK: - Actions | |
func update(with progress: Progress) { | |
self.progress = progress | |
} | |
private func calculateTimeRemaining() { | |
guard let progress = self.progress else { | |
estimatedTimeRemaining = nil | |
return | |
} | |
lastSpeed = progress.completedUnitCount - lastCompletedUnitCount | |
lastCompletedUnitCount = progress.completedUnitCount | |
averageSpeed = smoothingFactor * Double(lastSpeed) + (1 - smoothingFactor) * averageSpeed | |
estimatedTimeRemaining = Double(progress.totalUnitCount - progress.completedUnitCount) / averageSpeed | |
onEstimatedTimeRemainingUpdate?(estimatedTimeRemaining) | |
} | |
// MARK: - Timer | |
private func startRemainingTimeTimer() { | |
remainingTimeTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in | |
self?.calculateTimeRemaining() | |
} | |
} | |
private func stopRemainingTimeTimer() { | |
remainingTimeTimer?.invalidate() | |
remainingTimeTimer = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Download progress class for calculating download time remaining.
Usage: