如何解决从最小化状态 iOS 返回后调用计时器
我在获取当前位置后构建了一个实时时钟,然后从 api 响应中显示当前时间 - 我正在使用这些函数来显示当前时间。
func getCurrentTime() {
timer = Timer.scheduledTimer(timeInterval: 1,target: self,selector: #selector(self.currentTimeAfterFetchedTime),userInfo: nil,repeats: true)
}
@objc func currentTimeAfterFetchedTime(currentTime : Int) {
print("Timer Function gets Called \(Date())")
let formatter = DateFormatter()
formatter.dateFormat = "MMM d,h:mm:ss a"
DispatchQueue.main.async {
self.presentDayDateNTime.text = formatter.string(from: Date(timeIntervalSince1970: TimeInterval(self.dynamicCurrentDateNTime)))
self.dynamicCurrentDateNTime += 1
}
}
现在我想重新获取 api 并实时显示用户是否在最小化状态后回来。所以我添加了这个通知观察者来检查应用程序是否从最小化状态恢复 -
NotificationCenter.default.addObserver(self,selector: #selector(applicationComesInTheForeground),name: UIApplication.willEnterForegroundNotification,object: nil)
在我的 viewDidLoad() 中并定义它以获取位置并再次调用 api-
@objc func applicationComesInTheForeground() {
print("Called")
self.spinner.startAnimating()
fetchCurrentLocation()
}
我的应用程序在第一次启动时运行良好,但当它从最小化状态返回时,currentTimeAfterFetchedTime 在一秒内被调用一倍,我的时钟变得足够快,可以在 30 秒内计数 1 分钟。
我正在从 api 调用的完成处理程序调用 currentTimeAfterFetchedTime 函数-
DispatchQueue.main.async {
print("In Dispathch",self.currentDayData)
// MARK: - Dynamic time representation afetr fetching data from API
self.dynamicCurrentDateNTime = self.currentDayData.dt
self.getCurrentTime()
}
那么,我的问题是为什么我的计时器函数会在一秒钟内被调用两次?
解决方法
您应该在启动它之前在 getCurrentTime() 中重置旧计时器。
timer.invalidate()
,
添加以下观察者并在应用进入后台或非活动状态时使计时器失效。
NotificationCenter.default.addObserver(self,selector: #selector(applicationWillBecomeInactive),name: UIApplication.willResignActiveNotification,object: nil)
@objc func applicationWillBecomeInactive() {
print("application inactive")
timer.invalidate()
}
每当应用处于活动状态就可以启动定时器(如由你完成)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。