gpt4 book ai didi

swift - 将手机锁定在后台模式时停止时间

转载 作者:行者123 更新时间:2023-11-30 13:14:45 25 4
gpt4 key购买 nike

我想在手机锁定时停止计时器,我该怎么做?在代码中,我在他进入后台模式时设置了计时器,这样它就可以工作,但我不知道如何使手机锁定时时间停止。有人有想法吗?

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)

}
}

最佳答案

卢克有正确的答案,我只是要添加更多细节。在您的应用程序委托(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.
}

如果您需要恢复计时器处于事件状态,您可以在应用程序委托(delegate)中使用此方法

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?

关于swift - 将手机锁定在后台模式时停止时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com