I am trying to show a error message in a different view as in the below code
import Foundation
class apiCall: ObservableObject {
func getUsers(completion:@escaping ([ResultItem]) -> ()) {
let urlHeader=apiParams()
URLSession.shared.dataTask(with: urlHeader) { (data, response , error) in
let httpResponse = response as? HTTPURLResponse
guard let data = data else { return }
// print(String(data: data, encoding: .utf8) ?? "Invalid JSON")
do {
let result = try JSONDecoder().decode(Result.self,from: data)
completion(result.customerList)
} catch {
completion([])
errorview()
print("error:", error.localizedDescription)
}
}.resume()
}
}
errorView() is a view file which i want to display when the code enters inside catch block, but currently I am getting blank screen and the details inside errorView is not getting displayed
//errorview page
import SwiftUI
struct errorview: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct errorview_Previews: PreviewProvider {
static var previews: some View {
errorview()
}
}
I will modify the error message in this page once I am able to see this content from catch block
CodePudding user response:
try this approach as shown in this very basic example code, to "go" to the Errorview
when your ApiCall
, produces an error:
Adjust according to your needs:
struct ResultItem: Identifiable {
let id = UUID()
var name: String
// ...
}
struct Errorview: View {
@State var theError: APICallError?
var body: some View {
Text("Errorview: \(theError.debugDescription)")
}
}
enum APICallError: Error {
case decodingError
case outOfLuck
// ...
}
class ApiCall: ObservableObject {
func getUsers(completion:@escaping ([ResultItem], APICallError?) -> ()) {
let urlHeader = apiParams() // <-- a URL or URLRequest here
URLSession.shared.dataTask(with: urlHeader) { (data, response , error) in
guard let data = data else {
completion([], APICallError.outOfLuck)
return
}
do {
let result = try JSONDecoder().decode(Result.self,from: data)
completion(result.customerList, nil)
} catch {
completion([], APICallError.decodingError)
}.resume()
}
}
}
struct ContentView: View {
@State var theError: APICallError?
@State var actions: [Int] = []
var body: some View {
NavigationStack(path: $actions) {
Text("ContentView")
.navigationDestination(for: Int.self) { val in
Errorview(theError: theError)
}
}
.onAppear {
ApiCall().getUsers() { results, error in
if error != nil {
theError = error
actions = [1]
} else {
print("-----> results: \(results)")
// ....
}
}
}
}
}