Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

ios - Scheduling local notifications to repeat daily from tomorrow in Swift

I'm trying to schedule a local notification to fire every day (i.e. repeats), at a specific time, but from tomorrow.

i.e "Trigger a notifcation every day at 8pm, from tomorrow"

I've been using this SO question as guidance, and I believe I am doing what it says but I am still getting a notification today when I run the following code (if I schedule the notification before 8pm for instance):

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

import UserNotifications

  1. Check for user permission

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
    if $0 { } }
    
  2. Add notification

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...