Need strategy for using WeatherKit in the background

I asked a similar question a while back: https://developer.apple.com/forums/thread/730946

Since then I have a new Mac and new iPhone and so I now have the hardware to actually play with WeatherKit. I've worked my way past all the entitlements stuff and have been able to use and expand on online examples. Cool.

Trouble is, nearly every example you can find uses code designed to update the UI as fresh weather data is fetched. My app currently uses background URL fetches to obtain weather data, make some calculations and take appropriate actions, all in the background. Updating the UI was a separate challenge.

So which asynchronous tool is the right one for this? How can I quickly update my existing code to call WeatherKit instead of going to a weather site for a download?

I currently use something like a download task session:

 let weatherTask = session.downloadTask (with: URL(string: urlString)!)
    weatherTask.taskDescription = "weather"
     weatherTask.resume()

or a dataTask session:

var request = URLRequest(url: url)
 request.httpMethod = "GET"
 request.addValue("text/html", forHTTPHeaderField: "Content-Type")
let taskWeatherPOP = URLSession.shared.dataTask(with: request) { (data, response, error) in
 if error != nil {
        print("Error is \(String(describing: error))")
                                }
   if let POPData = data,
        let report = String(data: POPData, encoding: String.Encoding.utf8) {
if weatherReportPOP.contains("ServiceUnavailable") {
   print("A Weather POP report error")
      } else {
        weatherReportPOP = report
         
       }  // Close the IF service unavailable
    } // Closes the IF weather data is not nil
}  //  Close Task Weather
  taskWeatherPOP.resume()

Replies

I have succeeded in fetching weather data during an app refresh in the background! So it is indeed possible and it's been working great. My app already had background app refresh set up to launch a URL session, and I no longer need that now that WeatherKit can fetch the data I need.

My question now, before I push my new version out to the store, is how to handle any errors that WeatherKit might throw at me. I don't want the app to crash if the service goes down or whatever. The documentation describes a WeatherError but I'm confused over how to implement that. Need an example