ios – Sending a POST request through Swift


I am using Stripe API on the backend to process payments.
Here is the API URL: http://localhost:2000/charge/new

I am using SwiftUI for my iOS application to send a POST request to my API.

Here is my DTO object:

DTO:

struct ChargeObjectDTO : Codable{
    let vendorCustomerID: String;
    let currency: String;
    let chargeValue: CLongDouble;
    let confirmationStatus: Bool;
}

This is my request logic, I am trying to send a POST request with ChargeObjectDTO as an object:

PaymentsAPI:

    func createChargeRequest(chargeObj: ChargeObjectDTO) throws {
     
        var url = “http://localhost:2000/charge/new"
    
        do{
            //send request
            guard let myReqURL = URL(string: url) else { throw NetworkResponse.error };
            
            //Request
            var request = URLRequest(url: myReqURL);
            request.httpMethod = "POST";
            request.httpBody = try? JSONSerialization.data(withJSONObject: chargeObj);
            
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("token", forHTTPHeaderField: "Authorization")   //Here is where we add tokens, like authentication tokens
            
           
            URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
                    guard let httpResponse = response as? HTTPURLResponse,
                          httpResponse.statusCode == 200,
                          let myData = data,
                          let myJson = try? JSONSerialization.data(withJSONObject: data!, options: []) else{
                        let message = error?.localizedDescription ?? "Failed to Decode Response from Server"
                        print(message)
                        return
                    }
                    print("Created Payment Intent");
                    //DispatchQueue.main.async
                    
                }).resume();
                
                
                
        }catch{
            print(error)
        }
      
        
       
    }

Here is the UI screen
BookHotel:

    struct HotelBookingScreen: View {

        @State var myPaymentsAPI: PaymentsAPI = PaymentsAPI.init(chargeObjectDTO: ChargeObjectDTO(vendorCustomerID: "", currency: "", chargeValue: 0, confirmationStatus: false));
    
  

        var body: some View {

            Button(action: {
                                    try? myPaymentsAPI.createChargeRequest(chargeObj: ChargeObjectDTO(vendorCustomerID: "cus_12345”, currency: "USD", chargeValue: 100, confirmationStatus: true))
                                    
                                },  label: {
                                    Text("Confirm")
                                        .frame(maxWidth: 300)
                     });

        }
    }

What is the problem, why I am getting this error even though, I am decoding the JSON object?

The Error I am getting is:

Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write’

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img