-1

I am trying to set up local user notifications. I have a set of data that I want to be notified about on specific dates. The data is sorted in a class with information such as a name, information, and a date. Because of other code, I have established, I have formatted the data in the data as an integer. For example, if the date is May 5th, the associated date variable is 505, or if the date is December 11th, the associated date variable is 1211.

How could I create a function that sets off local user notifications on the specified dates by using the variables I have saved in my database?

The following code sorts the data by date and then places the next data in the 0th position.

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 trigger = UNCalendarNotificationTrigger(dateMatching: , repeats: false)
    let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)

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

I was planning on using an if-statement to set off the trigger in the function, something like if the current date is equal to the next date in the database, then I want to set off a notification; however, I don't know how to call a datecomponent that is equal to today. I also don't know if this will really work.

1 Answers1

0

Create an extension that will create date components from your data:

extension Int {

    var month: Int {
        return self / 100
    }

    var day: Int {
        return self % 100
    }
}

Create notification triggers based on date components:

let date = allDiscounts.list[myList[0]].dateApplied

let components = DateComponents(month: date.month,
                                day: date.day,
                                hour: 10, minute: 00, second: 00)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

let identifier = "\(date)"
let content = UNNotificationContent(
let request = UNNotificationRequest(identifier: identifier,
                                    content: content,
                                    trigger: trigger)
Nikola Ristic
  • 419
  • 4
  • 9