Repeating local notifications for specific days of week (Swift 3 IOS 10)

前端 未结 2 1527
灰色年华
灰色年华 2020-12-08 03:45

I am trying to schedule local notifications for specific days of week (e.g. Monday, Wednesday and etc) and then repeat them weekly. This is how the screen for setting notifi

2条回答
  •  暖寄归人
    2020-12-08 04:17

    You can use below function to get Date from selected picker value:

        //Create Date from picker selected value.
        func createDate(weekday: Int, hour: Int, minute: Int, year: Int)->Date{
    
            var components = DateComponents()
            components.hour = hour
            components.minute = minute
            components.year = year
            components.weekday = weekday // sunday = 1 ... saturday = 7
            components.weekdayOrdinal = 10
            components.timeZone = .current
    
            let calendar = Calendar(identifier: .gregorian)
            return calendar.date(from: components)!
        }
    
        //Schedule Notification with weekly bases.
        func scheduleNotification(at date: Date, body: String, titles:String) {
    
            let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: date)
    
            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
    
            let content = UNMutableNotificationContent()
            content.title = titles
            content.body = body
            content.sound = UNNotificationSound.default()
            content.categoryIdentifier = "todoList"
    
            let request = UNNotificationRequest(identifier: "textNotification", 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)")
                }
            }
        }
    

    After getting a value from picker pass picker hour, minute and year with selected week day as (Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, thursday = 5, Friday = 6, Saturday = 7) to function func createDate(weekday: Int, hour: Int, minute: Int, year: Int) to get notification fire date on weekly bases, and after getting date call function func scheduleNotification(at date: Date, body: String, titles:String) for schedule a notification.

提交回复
热议问题