使用iOS13.4,XCode11.4,Swift5.2,
您如何设置将在每个工作日(即星期一至星期五,而不是星期六和星期日)触发的本地通知?
我尝试了不同的Calendar-Component设置,但未成功解决工作日问题。
这是我到目前为止所做的...
如果警报需要在特定的日期:
Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: notificationDate)
如果警报需要每天重复:
Calendar.current.dateComponents([.hour, .minute], from: notificationDate)
如果警报需要在特定的工作日重复:
Calendar.current.dateComponents([.weekday, .hour, .minute], from: notificationDate)
等
但是您如何设置几个工作日(例如星期一至星期五的每个工作日??
这是精确的notificationDate示例的代码:
import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let content = UNMutableNotificationContent()
content.title = "My Notification Title"
content.categoryIdentifier = UUID().uuidString
var notificationIdentifier = "23224-23134-234234"
var notificationDate = Date(timeInterval: 30, since: Date())
let notificationTriggerKind = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: notificationDate)
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: notificationTriggerKind, repeats: false)
let notificationRequest = UNNotificationRequest(identifier: notificationIdentifier, content: content, trigger: notificationTrigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
notificationCenter.add(notificationRequest) {(error) in if let error = error { print("error: \(error)") } }
}
}
extension MyViewController: UNUserNotificationCenterDelegate {
// kicks in when App is running in Foreground (without user interaction)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// ...do your custom code...
completionHandler([.alert, .sound])
}
// kicks in when App is running in Foreground or Background
// (AND App is open) AND user interacts with notification
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse, withCompletionHandler
completionHandler: @escaping () -> Void) {
// ... do your custom code ....
return completionHandler()
}
}
您过得很好。
要在特定日期使用,您需要每天安排一个通知。
检查此示例:
extension Date {
public func getDateComponents() -> DateComponents {
let dateComponents = Calendar.current.dateComponents([ .hour, .minute, .second], from: self)
return dateComponents
}
}
var dateComponents = DateComponents()
dateComponents.hour = 9
dateComponents.minutes = 10
dateComponents.weekDay = 1
let workDays = 1...5
for day in workDays {
var dateComponents = date.getDateComponents()
dateComponents.weekday = day
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: repeats)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
self.notificationCenter.add(request) { (error) in
if let error = error {
}
}
}