Swift:暂停并恢复NSTimer

时间:2016-03-05 03:44:26

标签: swift nstimer

我知道之前已发布此消息,但我是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
}

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

2 个答案:

答案 0 :(得分:3)

简短回答:你不能。定时器无法暂停。

相反,您需要记录启动计时器时的当前时间:

# Create temporary directory for source and class files
with tempfile.TemporaryDirectory() as d:

    # Write source code
    srcpath = os.path.join(d.name, "myclass.java")
    with open(srcpath, "w") as srcfile:
        srcfile.write('source code goes here')

    # Compile source code
    subprocess.check_call(['javac', srcpath])

    # Run source code
    # Been a while since I've java-ed; you don't include .java or .class
    # when running, right?
    invokename = os.path.splitext(srcpath)[0]
    subprocess.check_call(['java', invokename])
... with block for TemporaryDirectory done, temp directory cleaned up ...

然后,当你想要暂停你的计时器时,让它失效并计算出还剩多少时间:

let startTime = NSDate.timeIntervalSinceReferenceDate()
let interval = 38.2
//Start your timer 
runFirstDropTimer = NSTimer.scheduledTimerWithTimeInterval(interval, 
  target: self, 
  selector: "runAnimation", 
  userInfo: nil, 
  repeats: false)

最后,当您想要恢复计时器时,请创建一个具有runFirstDropTimer.invalidate() let elapsed = NSDate.timeIntervalSinceReferenceDate() - startTime let remaining = interval - elapsed 值的新计时器。

答案 1 :(得分:0)

迅速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()