使用本地通知 api 在 swift 3 中触发每周通知

Posted

技术标签:

【中文标题】使用本地通知 api 在 swift 3 中触发每周通知【英文标题】:Triggering a weekly notification in swift 3 using local notifications api 【发布时间】:2018-06-27 04:56:15 【问题描述】:

我想在每周一晚上 7:00 触发每周通知。

我看到这样的代码:

let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
    我应该将起始日期设置为什么? 还需要现在日期吗?

我正在使用 ios 10+ 和 swift 3。

【问题讨论】:

【参考方案1】:

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

            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 like = 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
            

        

【讨论】:

再一次,我希望所有星期一晚上 7 点你的答案都没有显示 每周一晚上 7 点是的 在需要添加时间间隔 var dateStart = Date() dateStart = dateStart.addingTimeInterval(TimeInterval(604800)) 并生成与这些间隔通知 你好 @cdub 请立即检查并添加 timeinterwal【参考方案2】:

我使用了以下日期扩展名:

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>)

【讨论】:

【参考方案3】:

您可以在DateComponents中设置weekdaytime,您可以收到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)")
            
        
    

【讨论】:

【参考方案4】:

需要另一个触发器重载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://***.com/a/49561764/4601900

【讨论】:

如何设置为星期一晚上 7:00?我想要每周一次

以上是关于使用本地通知 api 在 swift 3 中触发每周通知的主要内容,如果未能解决你的问题,请参考以下文章

每 X 天本地通知 - Swift

Swift 3 本地通知未触发

Swift 3 - 本地通知的 didReceiveRemoteNotification 函数未触发

UNUserNotificationCenter Swift - 在特定情况下未触发本地通知

单元测试本地通知

不同日期的本地通知 Swift 3