UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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()

2      

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

2      

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

2      

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
    }
}

2      

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 April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.