连续重复功能,而不是使

时间:2017-09-08 00:53:19

标签: ios if-statement swift3 timer func

如何连续重复此功能而不是使其失效?我已经在代码底部标出了else部分,它目前只是显示一个标题而不是重复整个功能。

func handleTimer(_ timer: Timer) {
    if let currentPhase = self.phasesInProgress.last, let timerStart = timerStart {
        debugPrint("Current Phase: \(currentPhase.title)")

        let currentPhaseEndTime = TimeInterval(currentPhase.endTime)
        let elapsedTime = abs(timerStart.timeIntervalSinceNow)
        debugPrint("Elapsed Time: \(elapsedTime)")

        if elapsedTime > currentPhaseEndTime {
            debugPrint("Phase over current > \(currentPhaseEndTime), going to next.")
            self.phasesInProgress.removeLast()
            handleTimer(timer)
        } else {
            let phaseElapsed = elapsedTime - currentPhase.startTime
            let duration = currentPhase.endTime - currentPhase.startTime
            phaseTimeElapsedChanged(phaseElapsed, duration)
            phaseChanged(currentPhase.title)
        }

   // } else {
   //     self.timer?.invalidate()
   //     self.completion()
    }

这是计时器部分,但它没有重复该功能。

 func start() {
    phasesInProgress = phases.reversed()
    timerStart = Date()
    let aTimer = Timer(timeInterval: 1.0, repeats: true, block: { [weak 
 self] (blockTimer) in
        self?.handleTimer(blockTimer)
    })
    timer = aTimer
    RunLoop.current.add(aTimer, forMode: .defaultRunLoopMode)
    aTimer.fire()
}

这是init

的部分
init(settings: MeditationSettings, phaseChangedBlock: @escaping StringClosure, timeChangedBlock: @escaping DoubleDoubleClosure, completion: @escaping  VoidClosure) {
    self.phaseChanged = phaseChangedBlock
    self.phaseTimeElapsedChanged = timeChangedBlock
    self.completion = completion

    addPhase(with: "Breathe In", duration: settings.breathIn)
    addPhase(with: "Hold", duration: settings.breathInHold)
    addPhase(with: "Breathe Out", duration: settings.breathOut)
    addPhase(with: "Hold", duration: settings.breathOutHold)


}

2 个答案:

答案 0 :(得分:0)

您正在尝试使用Timer来重复某个功能,因此首先需要在您的班级上创建Timer属性

var myTimer: Timer!

之后,必须实例化Timer并指示它在所需的时间间隔内执行所需的选择器

myTimer = Timer.scheduledTimer(timeInterval: 5, 
                                     target: self,
                                   selector: #selector(functionToExecute),
                                   userInfo: nil,
                                    repeats: true)

因此通常会创建该函数

func functionToExecute() {
    // perform your tasks here
}

最后,当您完成代码执行后,您只需要使Timer无效。例如,您可以使viewDidDisappear()方法无效。

myTimer.invalidate()

答案 1 :(得分:0)

在主线程中启动计时器,如下所示:

func start() {
    phasesInProgress = phases.reversed()
    timerStart = Date()
    var aTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { [weak self] (blockTimer) in
        self?.handleTimer(blockTimer)
    })
    timer = aTimer
    RunLoop.current.add(aTimer, forMode: .defaultRunLoopMode)
    aTimer.fire()
}