代码之家  ›  专栏  ›  技术社区  ›  Garret Koontz

使用CoreData属性创建UILocalNotifications

  •  0
  • Garret Koontz  · 技术社区  · 7 年前

    在我的iOS应用程序中,我试图创建一个 localNotification 在事件开始前15分钟通知用户。然而,我被卡住了。我正在使用 CoreData 存储数据。我有一个 Appointment 可以创建的对象。A. date 约会 对象我真的被它困住了。我不知道如何设置 timeInterval 以及通知过程的其余部分。

    我不知道如何设置 时间间隔 约会

    func scheduleNotifications() {
        let content = UNMutableNotificationContent()
        guard let client = client, let name = client.name, let formula = formula, let date = formula.date else { return }
        content.title = "BookMe"
        content.subtitle = ""
        content.body = "Your appointment with \(name) will begin soon."
        content.badge = 1
    
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: ??, repeats: false)
    

    编辑:这是我拥有的,但什么都没有。

    let date = formula.date
    let fireDate = Calendar.current.date(byAdding: DateComponents(minute: -15), to: date as Date)
    guard let timeInterval = fireDate?.timeIntervalSince(Date()) else { return }
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
    
    let request = UNNotificationRequest(identifier: self.timerUserNotificationIdentifier, content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Abizern    7 年前

    据我所知,您正在寻找从现在到某个日期前15分钟之间的时间间隔,以便您可以在该日期前15分钟发出通知。

    下面是一个我在操场上偶然发现的例子

    // Create a date in the future - this is what you get from your own data object and I'm creating it here just so I have a date.
    let scheduledDate = Calendar.current.date(from: DateComponents(year: 2017, month: 09, day: 22, hour: 22))!
    
    // Create a date 15 minutes earlier than your shcheduled date, this is when you want your notification to fire
    let fireDate = Calendar.current.date(byAdding: DateComponents(minute: -15), to: scheduledDate)!
    
    // Then just work out the time interval between the fire date and now to get the time interval
    let timeInterval = fireDate.timeIntervalSince(Date())
    

    编辑以添加

    now timeIntervalSince1970 -“日期对象与1970年1月1日00:00:00 UTC之间的间隔。”UNIX时间戳或 timeIntervalSinceReferenceDate -“日期对象与2001年1月1日00:00:00 UTC之间的间隔。”

    无论你做什么,都要抵制直接添加或删除秒数来修改日期的诱惑,改用DateComponents。