Learn Courses My Dashboard

API Call Error: **failed to convert The data couldn’t be read because it isn’t in the correct format.**

Hello, I am getting this error I have no idea how fix and would appreciate some assistance please:

failed to convert The data couldn’t be read because it isn’t in the correct format.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let url = "https://www.goedash.com/_functions/quoteapi/quote"
        getData(from: url)
    }
    
    private func getData(from url: String) {
        
        let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
            
            guard let data = data, error ==  nil else {
                print("something went wrong")
                return
            }
            
            // have data
            var result: Quote?
            do {
                result = try JSONDecoder().decode(Quote.self, from: data)
            }
            catch {
                print("failed to convert \(error.localizedDescription)")
            }
            
            guard result != nil else {
                return
            }
            
            print(result!.brandName.codingKey.stringValue)
        
        })
            task.resume()
    }

}

{
  "pickup": {
    "street": "26 Broadway",
    "city": "New York City",
    "state": "NY",
    "postalCode": "10004",
    "country": "US",
    "latitude": 40.716038,
    "longitude": -74.00631,
    "unit": "104B",
    "instructions": "Use back entrance"
  },
  "dropoff": {
    "street": "312 Broadway",
    "city": "New York City",
    "state": "NY",
    "postalCode": "10004",
    "country": "US",
    "latitude": 40.24377,
    "longitude": -74.10277,
    "unit": "Suite 300",
    "instructions": "Leave with security guard"
  },
  "quoteExternalReference": "basket_e699aece",
  "pickupTime": "2015-09-22T18:30:00.000Z",
  "dropoffTime": "2015-09-22T18:30:00.000Z",
  "controlledContents": "Alcohol,Tobacco",
  "allowedVehicles": "Walker,Bicycle,DeliveryBicycle,Car,Van",
  "orderValue": 22.5,
  "brandName": "BigBellyBurger",
  "currency": "USD",
  "storeId": "Store-12345"
}

import Foundation

// MARK: - Quote
struct Quote: Codable {
    let pickup, dropoff: Location
    let quoteExternalReference, pickupTime, dropoffTime, controlledContents: String
    let allowedVehicles: String
    let orderValue: Double
    let brandName, currency, storeID: String

    enum CodingKeys: String, CodingKey {
        case pickup, dropoff, quoteExternalReference, pickupTime, dropoffTime, controlledContents, allowedVehicles, orderValue, brandName, currency
        case storeID = "storeId"
    }
}

// MARK: - Dropoff
struct Location: Codable {
    let street, city, state, postalCode: String
    let country: String
    let latitude, longitude: Double
    let unit, instructions: String
}

Are you sure you’re receiving any data from the API call? When I paste that URL into Safari, I get nothing back.

When I use the JSON and code you posted in a playground, it works fine.

I’m not receiving anything in XCODE project. Just that error.

It’s a “POST” not a “GET. So far I my short experience “GET” can show up in the browser and ”POST” has always never shoo-in browsers. But when I use The Postman software it’s shows up just fine when it’s in a lost setting. …Having said that is my code setup for. “POST” formate? If not how might I do that.

So I found this code for “POST” but I can’t get it to work. Could you take a shot:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        
        postRequest()
    }
    
    func postRequest() {
      
      // declare the parameter as a dictionary that contains string as key and value combination. considering inputs are valid
      
        let parameters = Bundle.main.path(forResource: "quote", ofType: "json")
      
      // create the url with URL
      let url = URL(string: "https://www.goedash.com/_functions/quoteapi/quote")! // change server url accordingly
      
      // create the session object
      let session = URLSession.shared
      
      // 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 {
        // convert parameters to Data and assign dictionary to httpBody of request
          request.httpBody = try JSONSerialization.data(withJSONObject: parameters!, options: .prettyPrinted)
      } catch let error {
        print(error.localizedDescription)
        return
      }
      
      // create dataTask using the session object to send data to the server
      let task = session.dataTask(with: request) { data, response, error in
        
        if let error = error {
          print("Post Request Error: \(error.localizedDescription)")
          return
        }
        
        // ensure there is valid response code returned from this HTTP response
        guard let httpResponse = response as? HTTPURLResponse,
              (200...299).contains(httpResponse.statusCode)
        else {
          print("Invalid Response received from the server")
          return
        }
        
        // ensure there is data returned
        guard let responseData = data else {
          print("nil Data received from the server")
          return
        }
        
        do {
          // create json object from data or use JSONDecoder to convert to Model stuct
          if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: Any] {
            print(jsonResponse)
            // handle json response
          } else {
            print("data maybe corrupted or in wrong format")
            throw URLError(.badServerResponse)
          }
        } catch let error {
          print(error.localizedDescription)
        }
      }
      // perform the task
      task.resume()
    }
}

I have yet to successfully update(“POST”) data in my database using this post method. Please help.