0

enter image description here

I want to send local notifications between 10A.M to 10P.M repeating every 2hours(user input) for the user selected days.

    var dateComponents = DateComponents()
    dateComponents.hour = 10
    dateComponents.minute = 00
    let userCalendar = Calendar.current
    var dateStart = userCalendar.date(from: dateComponents)
    var dateComponent = DateComponents()
    dateComponent.hour = 22
    dateComponent.minute = 00
    var dateEnd = userCalendar.date(from: dateComponent)

      while dateStart < dateEnd {
     //Add repeating hours start time
        UserDefaults.standard.set(self.txtField.text, forKey: "hoursSendary")
        let Nohours = UserDefaults.standard.integer(forKey: "hoursSendary")
      dateStart = dateStart?.addingTimeInterval(TimeInterval(Nohours * 60 * 60))
        //Schedule notification With body and title.
    scheduleNotification(body: "Free your eyes", titles: "Screen Alarm",day: 1)
    }

func scheduleNotification( body: String, titles:String,day:Int) {
       UserDefaults.standard.set(self.txtField.text, forKey: "hoursSendary")
       let Nohours = UserDefaults.standard.integer(forKey: "hoursSendary")
       let date = Date(timeIntervalSinceNow:TimeInterval(Nohours * 60 * 60) )

       var components = DateComponents()
       components.weekday = day// sunday = 1 ... saturday = 7
       components.weekdayOrdinal = 10
       components.timeZone = .current
       components.hour = Nohours
       let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
       let content = UNMutableNotificationContent()
       content.title = titles
       content.body = body
       content.sound = UNNotificationSound.default
       content.categoryIdentifier = "ScreenAlarm"
       let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)
       UNUserNotificationCenter.current().delegate = self
      //UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
       UNUserNotificationCenter.current().add(request) {(error) in
         if let error = error {
           print("Uh oh! We had an error: \(error)")
         }
       }
     }

How can I pass the user selcted days, I have a collection view with days and I'm doing this stuff inside the didselect method.

0 Answers0