安排本地通知从明天起在Swift中重复

时间:2017-07-02 15:30:06

标签: ios swift uilocalnotification unnotificationtrigger

我试图在特定时间安排本地通知(即重复),但从明天开始。

即"每天晚上8点开始通知,从明天开始#34;

我一直在使用this SO问题作为指导,我相信我正在做它所说的但我今天仍然收到通知,当我运行以下代码时(如果我之前安排通知)例如晚上8点):

    func testDateNotification(){

    let content = UNMutableNotificationContent()
    content.title = "Test"
    content.body = "This is a test"
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())

    let userCalendar = Calendar.current
    var components = userCalendar.dateComponents([.hour, .minute], from: tomorrow!)

    components.hour = 20
    components.minute = 00


    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if ((error) != nil){
            print("Error \(String(describing: error))")
        }
    }

}

1 个答案:

答案 0 :(得分:0)

import UserNotifications

  1. 检查用户权限

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
    if $0 { } }
    
  2. 添加通知

     let fromDate = Date(timeIntervalSince1970: Double(0.0))
    
     let dateComponent = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fromDate)
    
     let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
     print(trigger.nextTriggerDate() ?? "nil")
    
     let content = UNMutableNotificationContent()
     content.title = "title"
     content.body = "body"
     let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
     UNUserNotificationCenter.current().add(request) { 
         if let error = $0 {
             print(error)
             return
         }else { 
             print("scheduled") 
         }
     }