Запуск еженедельного уведомления в Swift 3 с использованием локальных API уведомлений - PullRequest
0 голосов
/ 27 июня 2018

Я хочу вызвать еженедельное уведомление, которое отправляется по понедельникам в 7:00 вечера.

Я вижу такой код:

let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
  1. Как установить дату начала?
  2. Также должна ли дата быть в настоящем?

Я пользуюсь iOS 10+ и swift 3.

Ответы [ 4 ]

0 голосов
/ 27 июня 2018

Вы можете установить weekday и time в DateComponents, вы можете получить уведомление для every monday at 7:00 PM, а также установить Repeat = "true"

func setupNotificationReminder() {
        let title:String = "Your reminder text goes here"
        var calendarComponents = DateComponents()
        calendarComponents.weekday = 2
        calendarComponents.hour = 19
        calendarComponents.second = 0
        calendarComponents.minute = 0

        // create a corresponding local notification
        let trigger = UNCalendarNotificationTrigger(dateMatching: calendarComponents, repeats: true)
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = "body"
        content.sound = UNNotificationSound.default()
        content.categoryIdentifier = "YourApp"

        let request = UNNotificationRequest(identifier: "NotificationAtGivenTime", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print("Uh oh! We had an error: \(error)")
            }
        }
    }
0 голосов
/ 27 июня 2018

Пройдите дату, по которой вы хотите создать локальное уведомление

            let strDate = (data as AnyObject).value(forKey: "not_date") as? String
            let dateformatter = DateFormatter()
            dateformatter.dateFormat = "yyyy-MM-dd hh:mm a"
            let notidate = dateformatter.date(from: strDate!)

вам необходимо сначала указать stattnotificationdate, например = 2018-06-25 07:00 PM, после того как вам нужно добавить интервал времени

var dateStart = Date() 
dateStart = dateStart.addingTimeInterval(TimeInterval(604800))

и генерировать уведомления с этими интервалами

//MARK:- Schedule Notification with Daily bases.
        func scheduleNotification(at date: Date, body: String, titles:String) {
            let triggerDaily = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)

            if #available(iOS 10.0, *) {
                let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
                let content = UNMutableNotificationContent()
                content.title = titles
                content.body = body
                content.sound = UNNotificationSound.default()
                content.categoryIdentifier = "HardikBar"

                let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request) {(error) in
                    if let error = error {
                        print("Uh oh! We had an error: \(error)")
                    }
                }
            } else {
                // Fallback on earlier versions
            }

        }
0 голосов
/ 27 июня 2018

Я использовал ниже расширение для даты:

extension Date {

    static func today() -> Date {
        return Date()
    }

    func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {
        return get(.Next,
                   weekday,
                   considerToday: considerToday)
    }

    func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {
        return get(.Previous,
                   weekday,
                   considerToday: considerToday)
    }

    func get(_ direction: SearchDirection,
             _ weekDay: Weekday,
             considerToday consider: Bool = false) -> Date {

        let dayName = weekDay.rawValue

        let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }

        assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")

        let searchWeekdayIndex = weekdaysName.index(of: dayName)! + 1

        let calendar = Calendar(identifier: .gregorian)

        if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {
            return self
        }

        var nextDateComponent = DateComponents()
        nextDateComponent.weekday = searchWeekdayIndex


        let date = calendar.nextDate(after: self,
                                     matching: nextDateComponent,
                                     matchingPolicy: .nextTime,
                                     direction: direction.calendarSearchDirection)

        return date!
    }

}

Это можно использовать для получения любого следующего или предыдущего дня недели от контрольной даты. Сначала вам нужно получить следующий понедельник, а затем установить UNCalendarNotificationTrigger, как показано ниже:

    var triggerDaily = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date().next(Date.Weekday.monday, considerToday: true))
    triggerDaily.hour = 19
    triggerDaily.minute = 0
    triggerDaily.second = 0


    if #available(iOS 10.0, *) {
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
        let content = UNMutableNotificationContent()
        content.title = "Title"
        content.body = "Body"
        content.sound = UNNotificationSound.default()
        content.categoryIdentifier = "Test"

        let request = UNNotificationRequest(identifier: "NotificationAt-\(String(describing: Calendar.current.date(from: triggerDaily))))", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print("Uh oh! We had an error: \(error)")
            }else {
                UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (arrayRequests) in
                    for request in arrayRequests {
                        if let calendarNotificationTrigger = request.trigger as? UNCalendarNotificationTrigger,
                            let nextTriggerDate = calendarNotificationTrigger.nextTriggerDate()  {
                            print("nextTriggerDate ===>>> \(nextTriggerDate)")
                        }

                        print("Request ===>>> \(String(describing: request.trigger))")
                    }


                })
            }
        }
    } else {
        // Fallback on earlier versions
    }

Вывод этого будет следующим:

nextTriggerDate === >>> 2018-07-02 13:30:00 + 0000

Запрос === >>> Необязательно ( Календарный год: 2018 Месяц: 7 День 2 Час: 19 Минута: 0 Второе: 0, повторяется: ДА>)

0 голосов
/ 27 июня 2018

Требуется еще одна перегрузка триггера TimeInterval

Так что вы можете получить

let timeInterval = dateOfNotification.timeIntervalSinceNow

Теперь

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: true)

Вы можете создать дату как

   if let date = Calendar.current.date(byAdding: .day, value: 7, to: self) {
      let date1 = Calendar.current.date(bySettingHour: hours, minute: minutes, second: 00, of: date)        
   }

Если вы хотите конкретный день, тогда обращайтесь https://stackoverflow.com/a/49561764/4601900

...