Time-related calculations

168 views Asked by At

I am writing an app using Swift 4. This apps first gets the current device time and puts it in a label (currentTimeLabel) in the format HH:mm.

It also gets a time in a different timezone from a firebase database as a String and puts this in two labels (currentSharedTimeLabel and timeReceivedFromServerLabel), also in the format HH:mm. The data retrieved from the server also includes the seconds. Clearly, this second time is not changing – but I want it to behave like the user would expect a time to behave, i.e. I want to add to the server time one second every second.

To achieve this, I first change the shared time from a string to a formatted time using this code:

let isoDate = timeReceivedFromServerLabel.text
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let mathDate = dateFormatter.date(from: isoDate!)

I then want to run a function, which adds a second every second to mathDate and puts the result in the currentSharedTimeLabel. Can you give me an idea on how to achieve this?

At the moment, and it is totally not working out, I am doing:

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))")

I am a bit lost intellectually on this one and I would appreciate any help.

(I hope I have made my issue clear and don't upset you with lacking or superficial information).

Edit 2: Code of Database observer (after update of 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) {
1

There are 1 answers

12
AudioBubble On BEST ANSWER

I think it sounds like a great use case for a Timer.

Say you have your current time converted in seconds stored in a currentTimeInSeconds variable.

You can update its value every time the view controller appears, and then update its value locally using a timer, until the user leaves the view controller, which would give the impression to the user that it works like an "actual" clock.

So you have your timer defined at the top within the scope of your class :

var timer = Timer()

You could initialize the timer in your viewDidAppear like so:

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

which would call your updateTimer() method every second :

func updateTimer() {
    currentTimeInSeconds += 1
}

The only thing that you need to do then is to convert the currentTimeInSeconds to a time in hh:mm:ss and you should be good to go !

Alternatively you could also use the Date's addTimeInterval() method to increment directly your Date by one second within your updateTimer() method, depending on when (if) you want to convert the NSNumber you get from Firebase Database to a Date or not.

Also don't forget to invalidate the timer when the user leaves the view controller (viewDidDisappear) :

timer.invalidate()