gpt4 book ai didi

swift : Pause and Resume NSTimer

转载 作者:行者123 更新时间:2023-11-28 10:20:31 25 4
gpt4 key购买 nike

我知道这之前已经发布过,但我是 swift 的新手,我想根据我的情况寻求帮助。所以我需要运行一个计时器,当 stopMusic() 被调用时(在我的应用程序中的某个地方),我需要暂停计时器,然后当 playMusic() 被调用时,我需要恢复计时器。

这是我所拥有的:

override func viewDidLoad() {

runFirstDropTimer = NSTimer.scheduledTimerWithTimeInterval(38.2, target: self, selector: "runAnimation", userInfo: nil, repeats: false)

}

func stopMusic() {
//Pause Timer
}

func playMusic() {
//Resume Timer
}

感谢您提供的任何帮助!!!

最佳答案

swift 5.

可恢复计时器:

class ResumableTimer: NSObject {

private var timer: Timer? = Timer()
private var callback: () -> Void

private var startTime: TimeInterval?
private var elapsedTime: TimeInterval?

// MARK: Init

init(interval: Double, callback: @escaping () -> Void) {
self.callback = callback
self.interval = interval
}

// MARK: API

var isRepeatable: Bool = false
var interval: Double = 0.0

func isPaused() -> Bool {
guard let timer = timer else { return false }
return !timer.isValid
}

func start() {
runTimer(interval: interval)
}

func pause() {
elapsedTime = Date.timeIntervalSinceReferenceDate - (startTime ?? 0.0)
timer?.invalidate()
}

func resume() {
interval -= elapsedTime ?? 0.0
runTimer(interval: interval)
}

func invalidate() {
timer?.invalidate()
}

func reset() {
startTime = Date.timeIntervalSinceReferenceDate
runTimer(interval: interval)
}

// MARK: Private

private func runTimer(interval: Double) {
startTime = Date.timeIntervalSinceReferenceDate

timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: isRepeatable) { [weak self] _ in
self?.callback()
}
}
}

用法:

private var playTimer: ResumableTimer?

playTimer = ResumableTimer(interval: 5.0) { [weak self] in
self?.doSomethingOnTimerFire()
}
playTimer?.start()

关于 swift : Pause and Resume NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com