日期未获取 phone Swift 4 的当前时间

Date not getting the current time of the phone Swift 4

我有这个函数可以计算从 phone 的当前分钟算起的时间量。我试图让计时器在这段特定时间后关闭。调用此函数的方式是通过用户在应用程序中翻转的开关,时间应自行重置。好吧,当之前翻转开关时,我的 NSDate 对象获取旧值时遇到了问题。有没有办法将 NSDate 对象重置为零?

这是我计算 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)
}

我在这里声明 Date() 对象

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]()

您的代码使用的实例变量 date 是一个 let 常量。您没有显示设置它的上下文,但我假设它是您 class 的实例变量。它是一个 let 常量这一事实意味着它永远不会在它声明的范围内改变。那几乎肯定是你的问题。