I'm trying to build a very simple iOS app.
I'm running into an issue with the app that I'm hopeful is an easy fix due to my lack of experience with Swift and SwiftUI. I'll jump to the issue before describing my app. I'm getting an NSURLErrorDomain Code=-999 "canceled" when attempting to move from a list item View in my NavigationStack to the DetailView:
Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://api.nasa.gov/planetary/apod?api_key=<removed>&end_date=2024-01-15&start_date=2024-01-10, NSErrorFailingURLKey=https://api.nasa.gov/planetary/apod?api_key=<removed>&end_date=2024-01-15&start_date=2024-01-10, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <3C846FA4-322F-40F6-AFA1-333588F17ABC>.<2>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3C846FA4-322F-40F6-AFA1-333588F17ABC>.<2>, NSLocalizedDescription=cancelled}
The reason I'm getting the error is I'm populating my NavigationStack using a @StateObject that is populated calling the URL in the error:
var body: some View {
NavigationStack {
List(listOfDailyImages.listOfDailyImages) { listItem in
NavigationLink(listItem.title, value: listItem)
}
.task {
await listOfDailyImages.retreiveListOfImages(startDate: startDate)
}
.navigationTitle("Daily Images")
.navigationDestination(for: NasaImageInformation.self) { listItem in
DailyImageDetailView(title: listItem.title, explanation: listItem.explanation, urlString: listItem.url)
}
Text("Total Days: \(listOfDailyImages.listOfDailyImages.count)")
}
}
When I tap on one of the list items the same call that was made to originally populate the list is called again. I've read about how if a URLRequest is in process when a view is destroyed, the URLRequest will be cancelled as well, so the error makes sense but I don't know how to fix it.
ObservableObject Code
@MainActor
class ListOfDailyImages: ObservableObject {
@Published private(set) var listOfDailyImages: [NasaImageInformation] = []
func retreiveListOfImages(startDate: Date) async {
let logger = Logger(subsystem: "org.curryware.nasaImages.ListOfDailyImages", category: "retreiveListOfImages")
let nasaAPIHandler = NasaApiHandler()
do {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .full
let timeToDisplay = dateFormatter.string(from: Date.now)
logger.debug("Calling listOfDailyImages - Time: \(timeToDisplay)")
listOfDailyImages = try await nasaAPIHandler.retrieveListOfImages(startDate: startDate)
} catch {
print(error)
}
}
}
Log Output
Calling listOfDailyImages - Time: 9:07:45 PM Eastern Standard Time
Calling listOfDailyImages - Time: 9:07:47 PM Eastern Standard Time
Attempting to get image: https://apod.nasa.gov/apod/image/2401/IC348_webb_960.jpg
The Attempting to get image: line is from the ObservableObject that is call to populate my detail view.
If anyone can point me in the right direction it would be greatly appreciated.