在 swift 中尝试停止计时器对象时出现致命错误

Fatal error when trying to stop timer object in swift

我目前正在为 Apple Watch 开发秒表。手表有两个接口和两个控制器。 TimerControllerSwitchControllerTimerController 运行计时器。我正在尝试停止 SwitchController 中的时间对象,因此创建了一个函数来停止我的 TimerController 中的计时器,我可以在 SwitchController 中访问它。问题是我在 TimerController 中遇到致命错误,我不知道为什么?

函数timeStopp()timerControllerreturns错误:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

查看此图片!

The interfaces

错误

滑动控制器 Swipe error

时间控制器 time error 1 time error 2

框架 Do i type it in here?

定时器控制器

import WatchKit
import Foundation

class TimerController: WKInterfaceController {
    @IBOutlet weak var timerOutlet: WKInterfaceTimer!

    var myTimer : Timer?
    var duration : TimeInterval = 45.0 //arbitrary number. 45 seconds

    var isPaused = false //flag to determine if it is paused or not
    var elapsedTime : TimeInterval = 0.0 //time that has passed between 
    pause/resume
    var startTime = NSDate()
    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        start_timer()   
        timerOutlet.setTextColor(UIColor.red)

        // Configure interface objects here.
    }

    func start_timer() {
        myTimer = Timer.scheduledTimer(timeInterval: duration, target: 
        self,selector: Selector(("timerDone")), userInfo: nil, repeats: 
        false)
        timerOutlet.setDate(NSDate(timeIntervalSinceNow: duration ) as 
        Date)
        timerOutlet.start()
    }
    func timerDone(){
        //timer done counting down
    }
    @IBAction func pauseResumePressed() {
        //timer is paused. so unpause it and resume countdown
        if isPaused{
            isPaused = false
            myTimer = Timer.scheduledTimer(timeInterval: duration - 
            elapsedTime, target: self, selector: 
            Selector(("timerDone")), userInfo: 
            nil, repeats: false)
            timerOutlet.setDate(NSDate(timeIntervalSinceNow: duration - 
            elapsedTime) as Date)
            timerOutlet.start()
            startTime = NSDate()
            //pauseResumeButton.setTitle("Pause")

        }
            //pause the timer
        else{
            isPaused = true

            //get how much time has passed before they paused it
            let paused = NSDate()
            elapsedTime += paused.timeIntervalSince(startTime as Date)

            //stop watchkit timer on the screen
            timerOutlet.stop()

            //stop the ticking of the internal timer
            myTimer!.invalidate()

            //do whatever UI changes you need to
            //pauseResumeButton.setTitle("Resume")
        }
    }

    override func willActivate() {
        // This method is called when watch view controller is about to 
        be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no 
        longer visible
        super.didDeactivate()
    }

}

已更新 SwipeController

import WatchKit
import Foundation


class SwipeController: WKInterfaceController {

    //@IBOutlet weak var myTimer: WKInterfaceTimer!
    var timer = TimerController()

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to 
be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no 
longer visible
        super.didDeactivate()
    }

    /stopp call is made here
    @IBAction func PauseButton() {
       timer.pauseResumePressed()
    }

}

更新

先导入通知中心。 在左侧的项目导航器中单击您的项目。一般去 "Linked Frameworks and Libraries"。单击 + 按钮并搜索通知中心,然后添加框架

Delete the whole TimerViewController and paste it with this: https://gist.github.com/rawandahmad698/a0095e584eaa4df278a23c92e71cca62

Delete the whole SwipeViewController and paste it with this: https://gist.github.com/rawandahmad698/9ac0b7a411b7e88ff44068938a0b250a

首先。在你的代码末尾添加这个到你的 TimerController:

import NotificationCenter
extension Notification.Name {
     static let stopTimer = Notification.Name("stopTimer")
}

之后。在您的 SwipeController 上编辑此行:

@IBAction func PauseButton() {
    // Post notification:
    let userInfo = ["foo": 1, "bar": "baz"] as [String: Any] // you could also transfer data

    NotificationCenter.default.post(name: .stopTimer, object: nil, userInfo: userInfo)
}

终于。在您的 TimerController 上将此添加到 willActivate()

NotificationCenter.default.addObserver(self, selector: #selector(stop_timer(notification:)), name: .stopTimer, object: nil)

不要忘记:在下面添加这个 willActivate()

func stop_timer(notification:NSNotification) {

    // Timer is paused. so unpause it and resume countdown
    if isPaused {
        isPaused = false
        timerOutlet.start()
        startTime = NSDate()

    } else {
        isPaused = true

        // Stop watchkit timer on the screen
        timerOutlet.stop()

        // Stop the ticking of the internal timer
        myTimer!.invalidate()

        // Do whatever UI changes you need to

    }

}

旧解决方案

您不能使尚未安排的计时器失效。 首先添加一个NSTimer:

import WatchKit
import Foundation

class TimerController: WKInterfaceController {
    @IBOutlet weak var timerOutlet: WKInterfaceTimer!
    var myTimer : NSTimer?
    var duration : NSTimeInterval = 45.0 //arbitrary number. 45 seconds

    // UPDATE
     var isPaused = false //flag to determine if it is paused or not
      var elapsedTime : NSTimeInterval = 0.0 //time that has passed between pause/resume
    var startTime = NSDate()
    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        timerOutlet.setTextColor(UIColor.red)


        // Configure interface objects here.
}

使用按钮暂停计时器:

 @IBAction func pauseResumePressed() {
    //timer is paused. so unpause it and resume countdown
    if isPaused{
        isPaused = false
        myTimer = NSTimer.scheduledTimerWithTimeInterval(duration - elapsedTime, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false)
        timerOutlet.setDate(NSDate(timeIntervalSinceNow: duration - elapsedTime))
        timerOutlet.start()
        startTime = NSDate()
        pauseResumeButton.setTitle("Pause")


      }
      //pause the timer
      else{
            isPaused = true

            //get how much time has passed before they paused it
            let paused = NSDate()
            elapsedTime += paused.timeIntervalSinceDate(startTime)

            //stop watchkit timer on the screen
            timerOutlet.stop()

            //stop the ticking of the internal timer
            myTimer!.invalidate()

            //do whatever UI changes you need to
            pauseResumeButton.setTitle("Resume")
        }
    }

启动计时器:

func start_timer() {
     myTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self,selector: Selector("timerDone"), userInfo: nil, repeats: false)
     timerOutlet.setDate(NSDate(timeIntervalSinceNow: duration ))
     timerOutlet.start()
}

timer 完成时。这个块被调用

func timerDone(){
       //timer done counting down
}