I ended up doing the below, which works but seems very fragile in case there is more than one download in progress for the URL session.
.backgroundTask(.urlSession("isStormy")) {
let session = … // A stored URL session, with the identifier "isStormy"
session.getAllTasks { tasks in
for task in tasks {
if task.state == .suspended || task.state == .canceling { continue }
// NOTE: It seems the task state is .running when this is called, instead of .completed as one might expect.
if let dlTask = task as? URLSessionDownloadTask {
if let url = dlTask.response?.url {
if let data = try? Data(contentsOf: url) {
// Parse the data here.
}
}
}
}
}
}
On a related note, in my use on iOS 16 beta 3, the new SwiftUI backgroundTask API only gets invoked about 65% of the time when I start a background download, as compared to 100% when using the URLSessionDownloadDelegate method below.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let data = try? Data(contentsOf: location) {
// Parse the data here.
}
}