【问题标题】:How to repeat a UNUserNotification every day?如何每天重复一次 UNUserNotification?
【发布时间】:2017-06-01 17:37:42
【问题描述】:

我正在尝试让用户安排通知以在每天的特定时间打开应用程序。到目前为止,我已经能够通过计算从现在到用户选择之间的时间来安排第一个通知,并在 X 秒内安排通知。但是,有没有一种方法可以让我将该通知设置为每天重复?如果您感到困惑,这是我的代码的一部分:

let newTime: Double = Double(totalDifference)
let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)
let request = UNNotificationRequest(identifier: "openApp", content: notif, trigger: notifTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
    if error != nil {
        print(error!)
        completion(false)
    } else {
        completion(true)
    }
})

非常感谢任何帮助

【问题讨论】:

标签: ios swift ios10 unusernotificationcenter


【解决方案1】:

在你的情况下,改变这一行:

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: true)

来自文档:

UNCalendarNotificationTrigger

在指定的日期和时间触发通知。你使用一个 UNCalendarNotificationTrigger 对象指定时间 通知的触发条件信息。日历 触发器可以触发一次,也可以触发多次。

NSDateComponents* date = [[NSDateComponents alloc] init];
date.hour = 8;
date.minute = 30; 
UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
                     triggerWithDateMatchingComponents:date repeats:YES];

斯威夫特:

var date = DateComponents()
date.hour = 8
date.minute = 30 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

【讨论】:

  • 底部代码正是我要找的,谢谢!
【解决方案2】:

SWIFT3

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    相关资源
    最近更新 更多