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?

import Foundation

let headers = [
    "x-rapidapi-key": "",
    "x-rapidapi-host": ""

let request = NSMutableURLRequest(url: NSURL(string: "")! 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) {
    } else {
        let httpResponse = response as? HTTPURLResponse



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.