swift - 与时间相关的计算

标签 swift nsdateformatter swift4 dateformatter

我正在使用 Swift 4 编写一个应用程序。该应用程序首先获取当前设备时间并将其以 HH:mm 格式放入标签 (currentTimeLabel) 中。

它还从 firebase 数据库中获取不同时区的时间作为字符串,并将其放入两个标签(currentSharedTimeLabeltimeReceivedFromServerLabel)中,格式也是 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 中的时间,您应该可以开始了!

或者,您也可以使用 DateaddTimeInterval() 方法在您的 中直接将您的 Date 增加一秒updateTimer() 方法,具体取决于您何时(如果)将从 Firebase 数据库获取的 NSNumber 转换为 Date

也不要忘记在用户离开 View Controller 时使计时器失效(viewDidDisappear):

timer.invalidate()

关于swift - 与时间相关的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264022/

相关文章:

swift - 无法将类型 'UserInfoEntity!.Type' 的值转换为预期的参数类型 'NSEntityDescription'

ios - 我是否可以发布其某些功能和 UI 因过期日期而更改的应用程序?

iOS:NSDateFormatter 当前日期,毫秒显示破折号

ios - NSDateFormatter : 12 hour formatted string can't converted in date when system date format is 24 hour in ios

ios - bar按钮项目文本在moonIcon中选择时会改变,就像swift 4中的Font Awesome一样

ios - 当我尝试使用带有迅速4的alamofire打印json结果时,我收到“错误域= kCFErrorDomainCFNetwork代码= 303”

ios - 分发应用程序时将文本文件放在哪里?

iphone - 从字符串 '2011-08-16T19:03:21.000Z' 获取日期

iOS Swift 4 - 在 tableview didSelectRowAt 上显示 Toast(或事件指示器)

swift - 如何将带有枚举的开关用于字符串