将NStimer发送到后台

时间:2016-12-20 17:10:00

标签: ios timer swift3

我的swift代码遇到了一些问题,我想验证一个按钮动作来启动一个计时器,我已经设法做了。

出现了一个问题,当用户发送背景时,它会暂停计时器,直到它被召回,然后从它停止的地方继续进行,那么应该是几小时的倒计时持续时间更长了!?!

我设法编写了一个计时器,当用户从后台返回应用程序时,该计时器现在会倒计时并启动。

我遇到的问题是我似乎无法将两者结合在一起!这开始变得非常令人沮丧,我现在能看到的只是行和代码行。

var timer = Timer()
var counter = 60
var password_Text: UITextField?

@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var timerButton: UIButton!

@IBAction func timerButton(_ sender: Any) {

    timerButton.isEnabled = false
    Timer.scheduledTimer(timeInterval: 43200, target: self, selector: #selector(myTimerTick), userInfo: nil, repeats: false)

    var password_Text: UITextField?

    let alertController = UIAlertController(title: "To start your own £10 APPi Hour, and get 2 Beers or 2 Cocktails", message: "get a memeber of the team to enter the password, but use it wisely, as you can only use it once per day. Remember with great power comes great responsability", preferredStyle: UIAlertControllerStyle.alert)

    let tickoff_action = UIAlertAction(title: "let the APPiness commence", style: UIAlertActionStyle.default) {
        action -> Void in

        if let password = password_Text?.text{
            print("password = \(password)")
            if password == "baruba151" {
                self.counter = 60
                self.timerLabel.text = String(self.counter)
                self.timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(appiHour.updateCounter), userInfo: nil, repeats: true)
            }

        } else {

            print("No password entered")

        }

    }

    alertController.addTextField { (txtpassword) -> Void in
        password_Text = txtpassword
        password_Text!.isSecureTextEntry = true
        password_Text!.placeholder = ""

    }

    alertController.addAction(tickoff_action)
    self.present(alertController, animated: true, completion: nil)

}

func myTimerTick() {
    timerButton.isEnabled = true
}

@IBOutlet weak var timerStartButton: UIButton!

func updateCounter() {

    counter -= 1
    timerLabel.text = String(counter)

    if counter == 0{

        timer.invalidate()
        counter = 0

    }

}

这是我验证计时器启动按钮和启动计时器的代码。

class ViewController: UIViewController {

// Setup a timer and a counter for use
var timer   = Timer()
var counter : TimeInterval = 0

var startDate: NSDate?

override func viewDidLoad() {

    @IBOutlet weak var timerStart: UIButton!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var timerStart: UIButton!
    @IBOutlet weak var timerStart: UIButton!
    @IBOutlet weak var timerStart: UIButton!
    // Set the initial date
    self.startDate = NSDate()
}

@IBOutlet weak var label: UILabel!

// Invalidest the timer, resets the counter and udpates the label
@IBAction func resetTimer(sender: AnyObject) {

    // Invalidate the timer, reset the label.
    self.timer.invalidate()
    self.label.text = ""
    self.counter    = 0
}

// A button that when pressed starts and stops the timer

@IBAction func timerBttnTouched(sender: AnyObject) {

    if self.timer.isValid {

        self.timer.invalidate()

    } else {

        self.setupTimer()
    }
}

// Does the actual counting everytime the timer calls this method
func timerFired() {

    let now = NSDate()
    let difference = now.timeIntervalSince(self.startDate! as Date)

    // Format the difference for display
    // For example, minutes & seconds
    let dateComponentsFormatter = DateComponentsFormatter()
    dateComponentsFormatter.string(from: difference)

    self.label.text = dateComponentsFormatter.string(from: difference)
}

// Setups a timer, adds it to the run loop and specifies what method should fire when the timer fires
func setupTimer() {

    // Sets up the timer, this will call the timerFired method every second
    self.timer = Timer(
        timeInterval: 1,
        target: self,
        selector: #selector(self.timerFired),
        userInfo: nil,
        repeats: true)

    // Add the timer to the run loop
    RunLoop.current.add(
        self.timer,
        forMode: RunLoopMode.defaultRunLoopMode)
}

}

这是将计时器发送到后台并带回正确时间的代码。

我尝试将2合并在一起并获得未解决的标识符错误,但未成功。就在这里。

class ViewController: UIViewController {

// Setup a timer and a counter for use
var timer   = Timer()
var counter : TimeInterval = 0
var password_Text: UITextField?




@IBOutlet weak var label: UILabel!
@IBOutlet weak var timerButton: UIButton!


// Invalidest the timer, resets the counter and udpates the label
@IBAction func resetTimer(_ sender: Any) {


    // Invalidate the timer, reset the label.
    self.timer.invalidate()
    self.label.text = ""
    self.counter    = 0
}


// A button that when pressed starts and stops the timer
// There's no pause/resume, so it's invalidated & created again
// But the counter value reamins the same
@IBAction func timerStart(_ sender: Any) {


    timerButton.isEnabled = false
    Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(myTimerTick), userInfo: nil, repeats: false)

    var password_Text: UITextField?

    let alertController = UIAlertController(title: "To start your own £10 APPi Hour, and get 2 Beers or 2 Cocktails", message: "get a memeber of the team to enter the password, but use it wisely, as you can only use it once per day. Remember with great power comes great responsability", preferredStyle: UIAlertControllerStyle.alert)

    let tickoff_action = UIAlertAction(title: "let the APPiness commence", style: UIAlertActionStyle.default) {
        action -> Void in

        if let password = password_Text?.text{
            print("password = \(password)")
            if password == "baruba151" {
                // Does the actual counting everytime the timer calls this method
                func timerFired() {

                    self.counter += 1
                    self.label.text = "\(self.counter)"
                }
            }

        } else {

            print("No password entered")

        }


    }

    alertController.addTextField { (txtpassword) -> Void in
        password_Text = txtpassword
        password_Text!.isSecureTextEntry = true
        password_Text!.placeholder = ""

    }




    alertController.addAction(tickoff_action)
    self.present(alertController, animated: true, completion: nil)

    if self.timer.isValid {

        self.timer.invalidate()

    }

    func myTimerTick() {
        timerButton.isEnabled = true
    }



    // Setups a timer, adds it to the run loop and specifies what method should fire when the timer fires
    func setupTimer() {

        // Setupt the timer, this will call the timerFired method every second
        self.timer = Timer(
            timeInterval: 0.5, // the rate in which the timer runs
            target: self,
            selector: #selector(self.timerFired),
            userInfo: nil,
            repeats: true)

        // Add the timer to the run loop
        RunLoop.current.add(
            self.timer,
            forMode: RunLoopMode.defaultRunLoopMode)
    }


}

}

提前感谢您的帮助。

0 个答案:

没有答案