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