NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How I can deal with response came from sdk

Forums > SwiftUI

Hi, I tied to fetch data from rapid API, but the rsponse contains only server details. How can I access data to show it? https://rapidapi.com/spoonacular/api/recipe-food-nutrition

import Foundation

let headers = [
    "x-rapidapi-key": "",
    "x-rapidapi-host": "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/quickAnswer?q=How%20much%20vitamin%20c%20is%20in%202%20apples%3F")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse)
    }
})

dataTask.resume()

   

You need to decode the data parameter that is passed to your completion handler.

   

I decodde it this way

  let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

                if let json = json {
                    print("JSON:\n" + String(describing: json) + "\n")
                }

But there is no structue to represent data Model

   

You have to supply a struct into which you can decode it. Something like this should work for this particular API call:

struct Response: Decodable {
    let answer: String
    let image: String
    let type: String
}

And you should be using Codable instead of JSONSerialization. So:

if let data = data {
    do {
        let response = try JSONDecoder().decode(Response.self, from: data)
        //do whatever with the decoded data
    }
    catch {
        print(error) // or whatever error handling you want to do
    }
}

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started 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.