I've looked all over but I can't find an answer to this question. I want a specific function to run at 6:00 am and 6:00 pm every day for a day/night mode in my app. This doesn't need to run in the background, just when the app is open, but I also want to prefom other functions of the app as well while it checks for the time.
You can do it like this. Just set a Date
with the Calendar
object. Put your specific time in military hours (from 0 to 24, with 0 being midnight) and Voila!, if your app is in the foreground and the specified time kicks in, you will see the function you used as the selector execute
Give it a shot and happy coding
override func viewDidLoad() {
super.viewDidLoad()
let calendar = Calendar.current
let now = Date()
let date = calendar.date(
bySettingHour: 23,
minute: 52,
second: 0,
of: now)!
let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
}
func runCode() {
print("Do whatever here")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With