Search code examples
swiftnsdate

Date not getting the current time of the phone Swift 4


I have this function that calculate the amount of time from the current minute of the phone. I am trying to have a timer go off after this specific amount of time. The way this function is called is through a switch that the user flips in the app and the time should reset it self. Well Im having trouble with my NSDate object getting old values when the switch was flipped before. Is there a way to reset the NSDate object to zero?

Here is my code for the calculating the current time of the phone.

func GetInitialTime(){
    finalTime = 0
    firstTimeCounter = 0
    timeInSeconds = 0
    let calendar = NSCalendar.current
    var minutes = calendar.component(.minute, from: date)
    var timeDifference = Int()

    if(minutes == 00 || minutes == 30) {
        print("The minute hand is at zero or thirty.")
    }
    else {
        print("The minute hand is NOT ar zero or thirty")
        print("The minute hand ia at:")
        if minutes < 30 {
            while (!(minutes == 30)) {
                minutes += 1
                timeDifference += 1
            }
            print("Therefore we make the minute hand at zero or thiry: ", minutes)
            print("The time difference we add to the minute is: ", timeDifference)
        }
        else {
            var i = minutes
            while i < 60 {
                i += 1
                minutes += 1
                timeDifference += 1
            }
            print("Therefore we make the minute hand at zero or thirty: ", minutes)
            print("The Time difference we add to the minute is: ", timeDifference)
        }

    }
    finalTime = Double(timeDifference * 60)
    print("The time difference in seconds is:", finalTime)
}

And I declare the Date() object here

let center = UNUserNotificationCenter.current()
let button = UIButton(type: UIButtonType.custom)
let date = Date()
var timeInSeconds = Int()
var finalTime = Double()
var halfHour = Double(1800)
var firstTimeCounter = Int()
var firstTimer = Timer()
var repeatingTimer = Timer()
var backgroundTask = BackgroundTask()
let dispatchGroup = DispatchGroup()
var urlWeb = "http://morrowrenewablesflowdata.com/iOSConnections/Notifications.php"
var downtimes = [String]()
var flows = [String]()

Solution

  • Your code is using an instance variable date that is a let constant. You don't show the context in which it's set, but I'm assuming it's an instance variable of your class. The fact that it's a let constant means it will never change in the scope in which it's declared. That's almost certainly your problem.