Bubba
Bubba

Reputation: 133

How to run code at a specific time in 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.

Upvotes: 6

Views: 5905

Answers (1)

Pato Salazar
Pato Salazar

Reputation: 1477

You can do it like this. Just set a Date with the Calendar object. Put your specific time in military hours (from 00:00 to 23:59, with 00:00 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")
}

Upvotes: 19

Related Questions