我正在使用 Swift 4 编写一个应用程序。该应用程序首先获取当前设备时间并将其以 HH:mm
格式放入标签 (currentTimeLabel
) 中。
它还从 firebase 数据库中获取不同时区的时间作为字符串,并将其放入两个标签(currentSharedTimeLabel
和 timeReceivedFromServerLabel
)中,格式也是 HH:mm
。从服务器检索的数据还包括秒数。显然,这第二次没有改变——但我希望它表现得像用户期望时间表现的那样,即我想每秒向服务器时间添加一秒。
为此,我首先使用以下代码将共享时间从字符串更改为格式化时间:
let isoDate = timeReceivedFromServerLabel.text
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let mathDate = dateFormatter.date(from: isoDate!)
然后我想运行一个函数,它每秒将一秒加到 mathDate
并将结果放入 currentSharedTimeLabel
。你能告诉我如何实现这一点吗?
目前,完全没有效果,我正在做:
for i in 0..<1314000 {
let j = i + 1
print(i, j)
let newCalcTime = mathDate?.addingTimeInterval(TimeInterval(j))
currentSharedTimeLabel.text = ("\(newCalcTime)")
print("\(String(describing: newCalcTime))")
我在这方面有点迷茫,如果有任何帮助,我将不胜感激。
(我希望我已经把我的问题说清楚了,不要因为缺乏信息或肤浅的信息而让您不高兴)。
编辑2:数据库观察者代码(更新Cocoapods后)
// SUBMIT BUTTON
let submitAction = UIAlertAction(title: "Submit", style: .default, handler: { (action) -> Void in
let textField = alert.textFields![0]
self.enterSharingcodeTextfield.text = textField.text
// SEARCHES FOR SHARING CODE IN DATABASE (ONLINE)
let parentRef = Database.database().reference().child("userInfoWritten")
parentRef.queryOrdered(byChild: "sharingcode").queryEqual(toValue: textField.text).observeSingleEvent(of: .value, with: { snapshot in
print(snapshot)
// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {
// DATA WAS NOT FOUND
// SHOW MESSAGE LABEL
self.invalidSharingcodeLabel.alpha = 1
} else {
// DATA WAS FOUND
for user_child in (snapshot.children) {
最佳答案
我认为这听起来像是 Timer
的一个很好的用例。
假设您将当前时间(以秒为单位)存储在 currentTimeInSeconds
变量中。
您可以在每次 View Controller 出现时更新它的值,然后使用计时器在本地更新它的值,直到用户离开 View Controller ,这会给用户留下它像“实际”时钟一样工作的印象.
因此您在类范围内的顶部定义了计时器:
var timer = Timer()
您可以像这样在 viewDidAppear
中初始化计时器:
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
它会每秒调用您的 updateTimer()
方法:
func updateTimer() {
currentTimeInSeconds += 1
}
您唯一需要做的就是将 currentTimeInSeconds
转换为 hh:mm:ss
中的时间,您应该可以开始了!
或者,您也可以使用 Date
的 addTimeInterval()
方法在您的 中直接将您的
方法,具体取决于您何时(如果)将从 Firebase 数据库获取的 Date
增加一秒updateTimer()NSNumber
转换为 Date
。
也不要忘记在用户离开 View Controller 时使计时器失效(viewDidDisappear
):
timer.invalidate()
关于swift - 与时间相关的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264022/