How to send a localNotification at a specific time everyday, even if that time has passed?

前端 未结 4 1998
执笔经年
执笔经年 2020-12-17 06:33

I have this code which runs a notification everyday at 7am, it gets the current date and then runs the notification when it gets to the set hour, my problem is if the time h

4条回答
  •  失恋的感觉
    2020-12-17 06:54

    Swift 5.1
    This one for example fires every day at 8:00 A.M. :

    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "Title"
    notificationContent.body = "This is a test"
    notificationContent.badge = NSNumber(value: 1)
    notificationContent.sound = .default
    
    var datComp = DateComponents()
    datComp.hour = 8
    datComp.minute = 0
    let trigger = UNCalendarNotificationTrigger(dateMatching: datComp, repeats: true)
    let request = UNNotificationRequest(identifier: "ID", content: notificationContent, trigger: trigger)
                    UNCenter.add(request) { (error : Error?) in
                        if let theError = error {
                            print(theError as! String)
                        }
                    }
    

提交回复
热议问题