After following along with the documentation and WWDC22 video on using the new SwiftUI Background Tasks API. My application was successfully updating in the background, then I ran into an issue where the data won't update resulting in a progress view showing and no new data being fetched but will eventually correct itself which doesn't seem right. See below screenshots below.
struct DemoApp: App {
@StateObject var viewModel = ViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(viewModel)
}
.backgroundTask(.appRefresh("myapprefresh")) {
await viewModel.fetchData()
}
}
}
class ViewModel: ObservableObject {
@Published var pokemon = PokeAPI(name: "", sprites: Sprites(frontDefault: ""))
func fetchData() async {
URLSession.shared.dataTaskPublisher(for: request)
.map{ $0.data }
.decode(type: PokeAPI.self, decoder: JSONDecoder())
.replaceError(with: PokeAPI(name: "", sprites: Sprites(frontDefault: "")))
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {_ in
}, receiveValue: { value in
self.pokemon = value
}).store(in: &cancellables)
}
}