iosswifttimerreal-time-clock

How to display real clock time after fetching time from API iOS


I've started learning Swift and iOS. For learning purpose I've crated a weather app using openweathermap api. In the api response, It gives me the time in Unix UTC time. I've converted the time (Int) to String using this function in extension -

func fromUnixTimeToTimeNDate() -> String {
    let date = Date(timeIntervalSince1970: TimeInterval(self))
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM d, h:mm:ss a"
    if let retData = dateFormatter.string(for: date) {
        return retData
    }
    return ""
}

So the output in the app looks like -

Sample Output

Now I want to make this uilabel ticking and display the current date and time and updates every seconds. Do I have to use timer() for this? Or there is other solution(s)?


Solution

  • Normally you would just use the system clock and the Date class' initializer Date(). That gives you the current date, and makes it easy to update the time as it changes. You could just create a repeating Timer that fires once a second and updates the time display

    If instead you want to use the current time from an API, and then keep updating that date every second, you'll have to do some math to calculate the updated time. (I would not recommend querying the API every second. That will keep the iOS device's radio at full power constantly, draining the battery quickly.)

    You will need to do some math to calculate the difference between the API call's number of seconds since 1970 and the internal clock's time interval since 1970, save that offset, and use it to adjust the time you get from calling Date(). (See the Date class' initializer init(timeIntervalSinceNow:), which can be used to get the date, but applying an adjustment.