在后台模式下锁定手机时停止时间

时间:2016-07-13 21:10:42

标签: swift locking

我想在手机锁定时停止我的计时器,以便我能做到这一点? 在代码中我设置定时器,当他进入后台模式,所以它可以工作,但我不知道如何使时间停止时手机被锁定。有人有个主意吗?

var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

override func viewDidLoad() {
    super.viewDidLoad()


    backgroundTaskIdentifier = UIApplication.shared().beginBackgroundTask {
        UIApplication.shared().endBackgroundTask(self.backgroundTaskIdentifier!)

    }

    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(LoangeController.cosumTime), userInfo: nil, repeats: true)
    startTime = NSDate.timeIntervalSinceReferenceDate()




}


func cosumTime() {

    let currentTime = NSDate.timeIntervalSinceReferenceDate()

    var elapsedTime: TimeInterval = currentTime - startTime

    let hours = UInt8(elapsedTime / 3600.0)

    elapsedTime -= (TimeInterval(hours) * 3600)

    let minutes = UInt8(elapsedTime / 60.0)

    elapsedTime -= (TimeInterval(minutes) * 60)

    let seconds = UInt8(elapsedTime)

    elapsedTime -= TimeInterval(seconds)


    //add the leading zero for minutes, seconds and millseconds and store them as string constants

    let strHours = String(format: "%02d", hours)
    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)

    let counttime =  "\(strHours): \(strMinutes): \(strSeconds)"

    timeconsum = counttime

    print("\(counttime)")


    if timeconsum == timeout {
        print("Remind TimeOut")
        let UUID = Foundation.UUID().uuidString

        Notification.addNotification(title: "TimeOut Put your Phone away", date: CurrentTime, uuid: UUID)

    }
}

2 个答案:

答案 0 :(得分:0)

您需要在app delegate

中添加applicationWillResignActive处理程序
func applicationWillResignActive(_ application: UIApplication) {
     //Pause timer
}

只要手机被锁定或进入睡眠状态,就应该调用此功能。

答案 1 :(得分:0)

卢克有正确的答案,我只想添加更多细节。在您的app delegate中,您可以添加

func applicationWillResignActive(application: UIApplication) {
  // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
}

如果您需要在活动状态下恢复计时器,则可以在应用程序委托中使用此方法

func applicationDidBecomeActive(application: UIApplication) {
     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

有关停止和启动计时器的更多信息,我建议使用此链接。祝你好运! How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?