Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code at a specific time in swift

Tags:

swift

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.

like image 478
Bubba Avatar asked Dec 11 '22 03:12

Bubba


1 Answers

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")
}
like image 73
Pato Salazar Avatar answered Jan 15 '23 12:01

Pato Salazar