简体   繁体   中英

how to track time in swift?

I need to make an app to track the employee attendance in an office, i will get the time date and time from the server as a string after that I need to update Time label, and then convert it time Date class for the next process.

在此处输入图片说明

class MainMenuVC: UIViewController {

    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var checkinStatusLabel: UILabel!

    var employee : Employee?
    var time : String?
    var date : String?

    override func viewDidLoad() {
        super.viewDidLoad()

        getDateTimeFromServer()

    }


func getDateTimeFromServer() {

// request to server to get date and time
// update the UI (date and time label)

}





}

but the problem is, the time data will always be the same, of course since I request only once to the server so the 'minute' will be static. it will be a problem for this attendance app.

let say when the user open that menu on 15:23, but when they actually tap the checkin button 7 minutes later, so the data that will be sent back to server is 15:23 (when the viewDidLoad firstly activated) not 15:30.

so how do i tackle this problem so the time will always be updated and will always be the same as the time from server for my UI label and for my Date class ?

This is a simple programming problem. You either need to

  1. Request the time from the server each time you need a time.

or

  1. Fetch the time from the server once, convert it to a Date , get the current date from your device, calculate the difference, and use that difference as an offset. The next time the user taps the checkin button, get the current Date from the device, add your offset, and use that as the current Date .

I leave it to you to figure out the details of how to do that. Take a look at the Date class reference in Xcode. There are methods that let you convert between Dates and numeric values, and apply numeric offsets to Dates .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM