0

Is there the concept of a WorkManager in SwiftUI like there is in Android. The use case is syncing data when there is not a reliable network. In this use case I have a Core Data database on the iPhone/iPad and updates can happen without a network connection, but I want to update the main server by calling a web api when network connectivity is available.

When a new record is created in iPhone Core Data, I want to queue up the change for when the network is available and update the local record with the results. If there is an error, I would like to save it as well. Ideally I could have some control over frequency and number of tries. I also don't want it to try if there is no network.

I also want the queued request to persist even when the app shuts down.

For example, using my iPhone I create a new record in Core Data. The phone is not connected to the network when I do, but the request is queued up, but does not try to call the web api because there is no network. I shut down the app and open it up later in a different location where there is network service. The call fails for some reason and I shut down the app again. I open the app later in an area where there is service and the web api call is tried again and succeeds.

My current API calls look like this:

let (data, response) = try await URLSession.shared.data(for: request)

if let response = response as? HTTPURLResponse {

    let json = try decoder.decode(T.self, from: data)

}

I've done a number of searches and perhaps my terms are wrong because I have not been able to find this scenario. I am new to iOS so it's likely I'm just searching for the wrong things.

I've seen videos like this one on concurrency with URLSession but it seems to be an immediate request running in the background and not a the specific situation of network connectivity and persisting of the request. I saw this post but it was a while ago and not answered.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
lcj
  • 1,355
  • 16
  • 37
  • Use [Background Task](https://developer.apple.com/documentation/backgroundtasks) this will accomplish your requirement. – Anbalagan D Jul 04 '23 at 20:03

0 Answers0