LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: Project 10 - Cupcake Corner - Checkout Failed

Forums > 100 Days of SwiftUI

Hi All,

I'm stuck on a problem with Project 10. I keep catching the generic Checkout Failed in the console rather than the expected response from reqres. I've looked a few times over this proect and can't figure out what the problem could be. I've also compared against the git files to see if I was missing something. Any help would be appreciated.

import SwiftUI

struct CheckoutView: View {
    @ObservedObject var order: Order

    @State private var confirmationMessage = ""
    @State private var showingConfirmation = false

    var body: some View {
        ScrollView {
            VStack {
                AsyncImage(url: URL(string: "https://hws.dev/img/cupcakes@3x.jpg"), scale: 3) { image in
                    image
                        .resizable()
                        .scaledToFit()
                } placeholder: {
                    ProgressView()
                }
                .frame(height: 233)

                Text("Your total is \(order.cost, format: .currency(code: "USD"))")
                    .font(.title)

                Button("Place Order") {
                    Task {
                        await placeOrder()
                    }
                }
                .padding()
            }
        }
        .navigationTitle("Check out")
        .navigationBarTitleDisplayMode(.inline)
        .alert("Thank you!", isPresented: $showingConfirmation) {
            Button("OK") { }
        } message: {
            Text(confirmationMessage)
        }
    }

    func placeOrder() async {
        guard let encoded = try? JSONEncoder().encode(order) else {
            print("Failed to encode order")
            return
        }

        let url = URL(string: "https://reqres.in/api/cupcakes")!
        var request = URLRequest(url: url)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"

        do {
            let (data, _) = try await URLSession.shared.upload(for: request, from: encoded)

            let decodedOrder = try JSONDecoder().decode(Order.self, from: data)
            confirmationMessage = "Your order for \(decodedOrder.quantity)x \(Order.types[decodedOrder.type].lowercased()) cupcakes is on its way!"
            showingConfirmation = true
        } catch {
            print("Checkout failed.")
        }
    }
}

struct CheckoutView_Previews: PreviewProvider {
    static var previews: some View {
        CheckoutView(order: Order())
    }
}

3      

Hi! If you followed tutorial step by step. You should have added @Published var data = Order() in class SharedOrder.

So in your placeOrder func you should used order.data like so:

guard let encoded = try? JSONEncoder().encode(order.data) else {
            print("Failed to encode order")
            return
        }

currently you have it as encode(order)

3      

Thanks for your help! I'll go back and review that. For some reason I don't have a SharedOrder class in my project so I'll have to see where I missed a step, though I do see the error in trying to encode the whole order and not the data.

Thank you!

3      

My bad! Cannot remember all the details of the project maybe it should be required to add extra functionality later. Share then you Order object so that others can see how you handle data. Maybe something wrong in that part.

3      

Thanks for the help so far. I think I figured it out. I can't remember what I did (it was late and I was looking at the code during a flight home) but I got the issue resolved.

3      

@ygeras Updating because I just finished working on the challenges and SharedOrder() appears in Hudson's tutorial for converting the class to a struct. I had a bugger of a time with that so I went to see his process for doing it and that's where the SharedOrder() class appears. I hadn't done the challenge when I first got the order failed message in the console.

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.