使用本地通知API在Swift 3中触发每周通知

时间:2018-06-27 04:56:15

标签: ios iphone swift swift3 uilocalnotification

我想触发一个每周一次的通知,该通知在星期一的晚上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 :(得分:2)

您想生成本地通知的通过日期

            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
            }

        }

答案 1 :(得分:1)

我已使用以下扩展名作为日期:

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,重复:YES>)

答案 2 :(得分:0)

需要另一个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

答案 3 :(得分:0)

您可以在weekday中设置timeDateComponents,既可以收到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)")
            }
        }
    }