重复本周特定日期的本地通知(Swift 3 IOS 10)

时间:2022-08-05 01:06:41

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 notifications looks:

我正在尝试为一周中的特定日期(例如星期一,星期三等)安排本地通知,然后每周重复一次。这是用于设置通知的屏幕的外观:

重复本周特定日期的本地通知(Swift 3 IOS 10)

User can select time for the notification and repeating days.

用户可以选择通知时间和重复日期。

My method for scheduling single non repeating notification looks like this:

我调度单个非重复通知的方法如下所示:

static func scheduleNotification(reminder: Reminder) {
    // Setup notification content.
    let content = UNMutableNotificationContent()

    //content.title = NSString.localizedUserNotificationString(forKey: "Reminder", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: reminder.reminderMessage, arguments: nil)
    content.sound = UNNotificationSound.default()


    // Configure the triger for specified time.
    // 
    let dateComponentes = reminder.dateComponents
    // TODO: Configure repeating alarm

    // For the testing purposes we will not repeat the reminder
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponentes, repeats: false)

    // Create the request object.
    let request = UNNotificationRequest(identifier: "\(reminder.reminderId)", content: content, trigger: trigger)

    // Schedule the request.
    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.add(request) { (error: Error?) in
        if let theError = error {
            print(theError.localizedDescription)
        }
    }
}

The date components are extracted from UIDatePicker widget and stored in reminder class:

日期组件从UIDatePicker小部件中提取并存储在提醒类中:

let date = reminderTimeDatePicker.date.addingTimeInterval(60 * 60 * 24 * 7)
let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: date)
...
reminder.dateComponents = components

I have an array selectedDays[Int] (as a property of reminder class) to hold info on days of week on which the notification should fire.

我有一个数组selectedDays [Int](作为提醒类的属性)来保存通知应该触发的星期几的信息。

How can I schedule notification on specific day of week and how to repeat it weekly?

如何在一周中的特定日期安排通知以及如何每周重复一次?

Even a single comment will be helpful, and thank you in advance.

即使是一条评论也会有所帮助,并提前感谢您。

2 个解决方案

#1


10  

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.

从选择器传递选择器小时,分钟和年份中获取值,选定的工作日为(星期日= 1,星期一= 2,星期二= 3,星期三= 4,星期四= 5,星期五= 6,星期六= 7) createDate(工作日:Int,小时:Int,分钟:Int,年份:Int)在每周基础上获取通知开火日期,并在获取日期调用函数func scheduleNotification(日期:日期,正文:字符串,标题:字符串)之后安排通知。

#2


2  

let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Wake up!", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Rise and shine! It's morning time!", arguments: nil) content.categoryIdentifier = "TIMER_EXPIRED"

let content = UNMutableNotificationContent()content.title = NSString.localizedUserNotificationString(forKey:“Wake up!”,参数:nil)content.body = NSString.localizedUserNotificationString(forKey:“Rise and shine!现在是早上的时间!”,参数:nil )content.categoryIdentifier =“TIMER_EXPIRED”

    let weekdaySet = [6,5]

    for i in weekdaySet {

    var dateInfo = DateComponents()
    dateInfo.hour = 16
    dateInfo.minute = 44
    dateInfo.weekday = i
    dateInfo.timeZone = .current

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request) { (error : Error?) in

    if let theError = error {
            print(theError.localizedDescription)
            }
        }
   }

#1


10  

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.

从选择器传递选择器小时,分钟和年份中获取值,选定的工作日为(星期日= 1,星期一= 2,星期二= 3,星期三= 4,星期四= 5,星期五= 6,星期六= 7) createDate(工作日:Int,小时:Int,分钟:Int,年份:Int)在每周基础上获取通知开火日期,并在获取日期调用函数func scheduleNotification(日期:日期,正文:字符串,标题:字符串)之后安排通知。

#2


2  

let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Wake up!", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Rise and shine! It's morning time!", arguments: nil) content.categoryIdentifier = "TIMER_EXPIRED"

let content = UNMutableNotificationContent()content.title = NSString.localizedUserNotificationString(forKey:“Wake up!”,参数:nil)content.body = NSString.localizedUserNotificationString(forKey:“Rise and shine!现在是早上的时间!”,参数:nil )content.categoryIdentifier =“TIMER_EXPIRED”

    let weekdaySet = [6,5]

    for i in weekdaySet {

    var dateInfo = DateComponents()
    dateInfo.hour = 16
    dateInfo.minute = 44
    dateInfo.weekday = i
    dateInfo.timeZone = .current

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request) { (error : Error?) in

    if let theError = error {
            print(theError.localizedDescription)
            }
        }
   }