I have a UIdatepicker used to selected a time(not a date). Once the time is selected i need to check to see if it the current time stored in the phones clock, if it is not then keep check until it is one it is execute this code:
takephoto = true
Example: I open the app at at 10:29 am, i select 10:31 as a time, at 10:31 take-hot = true
is executed.
I looked at this question, however it compares the date not the time. Any help is much appreciated.
I have also tried using this code but it does not work properly. I need the timer to be exact(within a second of the actual time), this code only works within a minute(of the actual time) :
var timercount = Timer()
viewdidload()
{
timercount = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
}
Func Check()
{
let nowdate = NSDate()(two date declare global Var)
let date2 = datePicker?.date
(chek the Time How Much Time Remain)
let elapsed = date2?.timeIntervalSince(nowdate as Date)
if Int(elapsed!) == 0
{
takePhoto = true
}
}
You are complicating things up by going
NSDate
. Use Swift's nativeDate
:Also, you should avoid this:
The reason is the timer may miss a beat (due to user quitting app, system too busy, rounding errors, etc.) that make that condition unmet. Always check if now is past the
fireDate
and if true, take the photo. If you want to take the photo only once, add another property to indicate that, like so: