0

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
      }

}
Community
  • 1
  • 1
  • Have a look into creating a date object you can compare using `DateComponents`. Here's an answer with some more info on that: http://stackoverflow.com/a/24090124/1843020 – Kilian Mar 05 '17 at 02:44
  • @KilianKoeltzsch I am not sure how to convert it to a time oriented count down instead of a day count down. I included a link to a question similar to the tin the question, i am also unsure how to incorporate that into my code –  Mar 05 '17 at 02:48

1 Answers1

3

You are complicating things up by going NSDate. Use Swift's native Date:

func check() {
    let fireDate = datePicker.date

    if fireDate < Date() {
        takePhoto = true
    }
}

Also, you should avoid this:

if Int(elapsed!) == 0 { } // don't

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:

if fireDate < Date() && !photoTaken {
    takePhoto = true
    photoTaken = true
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • I am geting an error that reads "binding type must have optional type, not 'Date'" with the arrow pointed under let –  Mar 05 '17 at 05:16
  • Sorry made a mistake. Took out the `guard` statement – Code Different Mar 05 '17 at 13:32
  • I have no errors however the app does not execute the code at the selected time. Should I use if fireDate = Date() instead of if fireDate < Date() – Oren Edrich Mar 05 '17 at 21:17
  • Guess which condition, `<` or `==`, has a higher chance of occurring? Check if your function is indeed firing every second – Code Different Mar 05 '17 at 23:08