TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Reply to this topic…

You need to create an account or log in to reply.

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.