我正在尝试根据日期列表向用户提供通知。当其中一个日期与当前日期匹配时,我希望用户收到通知。如果应用程序已经在运行,那么我当前拥有的代码效果很好。但是,如果用户关闭应用程序,则不再提供通知。
下面是我已经尝试过的代码:
func userNotification() {
let content = UNMutableNotificationContent()
let allDiscounts = discountBank()
let dateClass = theDate()
var my1 = 0
var myList = [Int]()
for i in 0...allDiscounts.list.count-1 {
if dateClass.todaysDate > allDiscounts.list[i].dateApplied {
my1 = i+1
}
}
myList.append(my1)
for i in my1+1...allDiscounts.list.count-1{
myList.append(i)
}
if my1>=1{
for i in 0...my1-1{
myList.append(i)
}
}
print(myList)
content.title = "Todays Deal at \(allDiscounts.list[myList[0]].businessName)"
content.body = allDiscounts.list[myList[0]].theDeal
content.sound = UNNotificationSound.default
let components = DateComponents(month:theDate().month, day:theDate().day, hour:11, minute:28)
if theDate().todaysDate == allDiscounts.list[myList[0]].dateApplied {
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}