无法将时差设置为本地通知的时间间隔

时间:2019-03-30 18:57:09

标签: swift xcode

我已经从两个时间点计算出了时差:

func timeDiff() {
    let time1 = currentTimeOutlet
    let time2 = alarmTimeOutlet

    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mma"

    let date1 = formatter.date(from: time1!.text!)
    let date2 = formatter.date(from: time2!.text!)

    var elapsedTime = date2!.timeIntervalSince(date1!)

    if (elapsedTime < 0) {
        elapsedTime = elapsedTime + 86400
        UserDefaults.standard.set(elapsedTime, forKey: "TIME")
    }
    else {
        UserDefaults.standard.set(elapsedTime, forKey: "TIME")
    }

    elapsedTimeSecOutlet.text = String(elapsedTime)
    let hours = floor(elapsedTime / 60 / 60)
    let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
    timeDiffOutlet.text = ("\(Int(hours)) hr and \(Int(minutes)) min")
}

单击按钮后,我试图将本地通知中的时间间隔设置为此计算出的时差(elapsedTime):

@IBAction func defaultOnAction(_ sender: UIButton) {
    defaultOffOutlet.isHidden = false
    timeDiff()

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Yay!")
        } else {
            print("Dh.")
        }
    }
    let content = UNMutableNotificationContent()
    content.title = "Rise & Shine"
    content.subtitle = "Let's start the day!!!!!!"

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: elapsedTime, repeats: false)

    let request = UNNotificationRequest(identifier: "timeElapsed", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

当我将timeinterval设置为整数(例如20.0)时,本地通知有效,但是当我将其替换为“ elapsedTime”时,xcode会提示我将其更改为 TimeInterval(elapsedTime)。 / p>

我将其更改为TimeInterval(elapsedTime)。但是,当我构建应用程序时,构建成功,但是一旦单击按钮,应用程序将崩溃。我检查了该按钮是否与其他代码一起使用,并且在将timeinterval重新更改为整数后可以正常使用。

有人有什么建议吗?是否可以将我的时间间隔设置为变量?

非常感谢您!

1 个答案:

答案 0 :(得分:0)

时差方法更新。试试此代码以了解时差。一分钟后我会收到通知

let time1 = NSDate() //update your time
let minutes1: TimeInterval = 1 * 60
let time2 = Date() + minutes1 //update your time

var formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let strdate1 = formatter.string(from: time1 as Date)
formatter.dateFormat = "HH:mm:ss"
let date1 = formatter.date(from: strdate1)

formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let strdate2 = formatter.string(from: time2)
formatter.dateFormat = "HH:mm:ss"
let date2 = formatter.date(from: strdate2)

var elapsedTime = date2!.timeIntervalSince(date1!)

if (elapsedTime < 0) {
    elapsedTime = elapsedTime + 86400
    UserDefaults.standard.set(elapsedTime, forKey: "TIME")
}
else {
    UserDefaults.standard.set(elapsedTime, forKey: "TIME")
}

希望这对您有所帮助。