应用程序在后台运行/暂停时继续倒数计时器

Mic*_*inh 4 background-process nstimer countdown ios swift

我有一个功能倒数计时器.

问题是当用户将应用程序放在后台时我需要继续倒计时.或暂停应用程序?我不确定描述此操作的正确术语是什么.

换句话说,用户打开应用程序并开始倒计时.用户应该能够使用其他应用程序,但倒计时仍在运行.此外,倒计时应该能够永久运行,直到完成或用户终止运行应用程序.

这是我的计时器的代码:

    class Timer{
var timer = NSTimer();
// the callback to be invoked everytime the timer 'ticks'
var handler: (Int) -> ();
//the total duration in seconds for which the timer should run to be set by the caller
let duration: Int;
//the amount of time in seconds elapsed so far
var elapsedTime: Int = 0;
var targetController = WaitingRoomController.self

var completionCallback: (() -> Void)!



/**
:param: an integer duration specifying the total time in seconds for which the timer should run repeatedly
:param: handler is reference to a function that takes an Integer argument representing the elapsed time allowing the implementor to process elapsed time and returns void
*/
init(duration: Int , handler : (Int) -> ()){
    self.duration = duration;
    self.handler = handler;
}

/**
Schedule the Timer to run every 1 second and invoke a callback method specified by 'selector' in repeating mode
*/
func start(){
    self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onTick", userInfo: nil, repeats: true);
}

/**
invalidate the timer
*/
func stop(){
    println("timer was invaidated from stop()")
    timer.invalidate();
}


/**
Called everytime the timer 'ticks'. Keep track of the total time elapsed and trigger the handler to notify the implementors of the current 'tick'. If the amount of time elapsed is the same as the total duration for the timer was intended to run, stop the timer.
*/


@objc func onTick() {
    //println("onTick")
    //increment the elapsed time by 1 second
    self.elapsedTime++;
    //Notify the implementors of the updated value of elapsed time
    self.handler(elapsedTime);
    //If the amount of elapsed time in seconds is same as the total time in seconds for which this timer was intended to run, stop the timer
    if self.elapsedTime == self.duration {
        self.stop();

    }
}
deinit{
    println("timer was invalidated from deinit()")
    self.timer.invalidate();
}
Run Code Online (Sandbox Code Playgroud)

}

Rol*_*som 7

我建议取消计时器并存储NSDate应用程序进入后台的时间.您可以使用此通知来检测应用程序转到后台:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "pauseApp", name: UIApplicationDidEnterBackgroundNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

然后取消计时器并存储日期:

func pauseApp(){
    self.stop() //invalidate timer
    self.currentBackgroundDate = NSDate()
}
Run Code Online (Sandbox Code Playgroud)

使用此通知检测用户返回:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "startApp", name: UIApplicationDidBecomeActiveNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

然后计算从存储日期到当前日期的差异,更新计数器并再次启动计时器:

func startApp(){
    let difference = self.currentBackgroundDate.timeIntervalSinceDate(NSDate())
    self.handler(difference) //update difference
    self.start() //start timer
}
Run Code Online (Sandbox Code Playgroud)

  • 使用这种方法很容易改变设备日期和黑客倒计时,怎么可能没有黑客攻击? (3认同)