GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Run code at a specific time - iOS17 edition

Forums > SwiftUI

I've always tried to figure out how to do the following (since way before Swift was a thing). To my (limited?) knowledge it can't be done. But Apple adds new things every year (widgets, extensions). So I think it's worth asking again.

func thisFunction() {
   print("And this prints")
}

The user would like to run that function at exactly 4:00pm, next Tuesday.

Can it be done?

2      

It's been possible since iOS 8, long before SwiftUI: https://developer.apple.com/documentation/dispatch/dispatchqueue/2300053-asyncafter

To understand how to use this method, read Paul's tutorials on Grand Central Dispatch.

2      

The GCD expects the app to be in the foreground state, which I guess the question is not really asking about.

If you need this level of precision, I think the best shot is silent remote notification that wakes up your app and hope the system won't delay this when received (battery life, no internet connection).

Next option are background tasks but that can easily have tolerance of a few hours.

2      

As with all my questions, I forget to put in one thing. Yes, run the function while the app is in the background.

Remote Notifications - I have looked into this in the past. I decided it wasn't trustworthy enough. First the app would have to have internet access when the user scheduled 4:00pm on Tuesday, and would also need internet access at 4:00pm on Tuesday. If they didn't, it wouldn't work, and the complaints would start.

Background Tasks - I also looked into this. It's on the whim of the operating system, so precise timing isn't available.

2      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. Unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a FREE crash course.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.