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
436 views
in Technique[技术] by (71.8m points)

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

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 has already passed the set run time then everyday it will run at the user current time not my time on 7am, here is my code

var dateFire: NSDateComponents = NSDateComponents()
var getCurrentYear = dateFire.year
var getCurrentMonth = dateFire.month
var getCurrentDay = dateFire.day

dateFire.year = getCurrentYear
dateFire.month = getCurrentMonth
dateFire.day = getCurrentDay
dateFire.hour = 7
dateFire.minute = 0
dateFire.timeZone = NSTimeZone.defaultTimeZone()


var calender: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date: NSDate = calender.dateFromComponents(dateFire)!

var localNotification = UILocalNotification()
localNotification.fireDate = date
localNotification.alertBody = "A new day has begun and a fresh layer on snow lies on the mountain! Can you beat your highscore?"
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay

UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

As you can see NSCalendarUnit.CaldendarUnitDay makes it run everyday at 7am. I don't know so that even if the time is after 7am the notification will still run the next day would be greatly appreciated

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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)
                UNUserNotificationCenter.current().add(request) { (error : Error?) in
                    if let theError = error {
                        print(theError.localizedDescription)
                    }
                }

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

...