Error: Cannot convert value of type '()' to expected argument type 'Data'

Hello,

I am trying to make a “POST” to my database but I have this error that is hindering my attempts to do so: Cannot convert value of type ‘()’ to expected argument type ‘Data’

it occurs around this block. Please help:

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

class ViewController: UIViewController {

   
    var quote: Quote?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
    }
   
    
    @IBAction func updateButton(_ sender: Any) {
        Task {
            await replaceBrandName()
        }
    }
    
    
    func replaceBrandName() async {
        guard let encoded = try? JSONDecoder().allowsJSON5.encode(to: quote as! Encoder) else {
            print("Faild to encode")
            return
        }
        
        // create the url with URL
        let url = URL(string: "https://www.goedash.com/_functions/quoteapi/quote")! // change server url accordingly
        
       
        
        // now create the URLRequest object using the url object
        var request = URLRequest(url: url)
        request.httpMethod = "POST" //set http method as POST
        
        // add headers for the request
        request.addValue("application/json", forHTTPHeaderField: "Content-Type") // change as per server requirements
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        
        do {
            let (data, _) =  try await URLSession.shared.upload(for: request, from: encoded )
        }
        
    }
    
}

encode(to:) does not return a value, so you are actually setting encoded to the encode(to:) method itself.

Then you try to upload encoded but the upload(for:from:delegate:) method of URLSession takes Data as its from parameter and you are giving it the encode(to:) function from above.

I’m not seeing a solution.

So… I am new to posting to a database using a url/api, the “POST” method. Could you share a method that uses just a text field and a button that actually works at posting to a database using the “POST” method?

Because I don’t have a solution to give you. If I did, I would have posted it.

But knowing why a problem occurred is the first step in figuring out your own solution.

So… I am new to posting to a database using a url/api, the “POST” method. Could you share a method that uses just a text field and a button that actually works at posting to a database using the “POST” method?

There have been tutorials on “GET” methods which have used successfully, but there are very few tutorials on “POST”. Assistance in getting a “POST” method to work would be greatly appreciated.

This series is about Vapor, but this video shows a POST request

1 Like