UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Changing views based on conditional IF statement

Forums > SwiftUI

I am using SwiftUI. So I have received a response from an API. Based on this response I want to display a view that corresponds to what condition the response equals. For example, I upload a photo to an API, I will get a response that will determine the type of flag that was uploaded. Based on the results from the flag, I want to display the view that corresponds with the flag and its country. My code:

struct CameraView: View {
    var body: some View {

    Button("Verify"){ 
                            let imageData: Data = image?.jpegData(compressionQuality: 0.1) ?? Data() 
                            let imageStr: String = imageData.base64EncodedString()
                            let url = URL(string: "URL")! 
                            var request = URLRequest(url: url)

                            request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
                            request.setValue("Token", forHTTPHeaderField: "Authorization")

                            let body: [String: Any] = [ 
                                "task_id" : "4b17-9f63-974c2f30beb9",
                                "records" : [
                                    [
                                        "_base64": imageStr
                                    ]
                                ]
                            ]
                            let bodyData = try? JSONSerialization.data(withJSONObject: body, options: [])

                            request.httpMethod = "POST"
                            request.httpBody = bodyData

                            let session = URLSession.shared 

                            session.dataTask(with: request) { (data, response, error) in
                                    if let response = response {
                                        print(response)
                                    }
                                   if let data = data {
                                        do {

                                            let ximilar = try? JSONDecoder().decode(Welcome.self, from: data)
                                            let condition = ximilar!.records.first?.bestLabel.name
                                            if condition == "UK"{
                                                // bring up UKView
                                            }
                                            if condition == "US"{
                                                // bring up USView
                                            }
                                            if condition == "Aus"{
                                                // bring up AUSView
                                            }
                                            if condition == "NZ"{
                                                // bring up NZView
                                            }
                                        }
                                    }

                           }.resume()
}
}

struct UKView: View {
   var body: some View {
      Text("Hello world")
   }
}
struct USView: View {
   var body: some View {
      Text("Hello world")
   }
}
struct AUSView: View {
   var body: some View {
      Text("Hello world")
   }
}
struct NZView: View {
   var body: some View {
      Text("Hello world")
   }
}

As I am fairly new to swift, I have no idea how to approach this issue. I have searched for solutions but they all result in errors within my code.

2      

There's a fair amount to unpack there, but its really not considered good practice to handle API calls within the body of a View. The body should be a declarative code describing the view.

The best practice for networking calls is to do them all in their own dedicated method and class. However if you dont do that you should move the networking code out of the view body and into a method.

Take a look at:

https://www.hackingwithswift.com/books/ios-swiftui/sending-and-receiving-codable-data-with-urlsession-and-swiftui

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.