NEW: Download Kickstart, the app that helps indie developers succeed on the App Store! >>

SOLVED: API integration help. Type mismatch for type Dictionary ....

Forums > SwiftUI

Hello, Good-day,

I'm looking for some advice on integrating with an API

The API returns this.

[
    {
        "id": "act.in",
        "name": "Act In",
        "date": "2023-04-27",
        "timestamped": true,
        "date_start": "2022-10-07",
        "date_end": "2023-04-27"
    },
    {
        "id": "act.del",
        "name": "Act Del",
        "date": "2023-04-27",
        "timestamped": true,
        "date_start": "2022-10-07",
        "date_end": "2023-04-27"
    }
]

I'm using Ducky to get the codable struct and I get this

struct Unknown: Codable {
  let id: String
  let name: String
  let date: String
  let timestamped: Bool
  let dateStart: String
  let dateEnd: String

  private enum CodingKeys: String, CodingKey {
    case id
    case name
    case date
    case timestamped
    case dateStart = "date_start"
    case dateEnd = "date_end"
  }
}

And I call the API like this


    let urlAPIAppGAnalytics = "https://api.app/v1/projects/" + connectUser + "/" + connectSlug + "/collections"
    guard let url = URL(string: urlAPIAppGAnalytics) else
    {
        print("Cannot connect")
        return("40x")
    }

    var urlRequestAppGAnalyticsID = URLRequest(url: url)

    let APIheadersAppGAnalyticsID = [
        "accept": "application/json",
        "Authorization": "Token " + connectToken
    ]

    urlRequestAppGAnalyticsID.allHTTPHeaderFields = APIheadersCrawlRate
    urlRequestAppGAnalyticsID.httpMethod = "GET"
    urlRequestAppGAnalyticsID.timeoutInterval = mv.mobApiTimeout
    urlRequestCrawlRange.cachePolicy = .useProtocolCachePolicy

    let (dataAppGAnalyticsID, responseAppGAnalyticsID) = try await URLSession.shared.data(for: urlRequestAppGAnalyticsID)

    guard (responseAppGAnalyticsID as? HTTPURLResponse)?.statusCode == 200
    else {
        print("Cannot connect")
        return("40x")
    }

    let AppGID = try JSONDecoder().decode(APIAppGAnalyticsID.self, from: dataAppGAnalyticsID)

Everything compiles but my error checking returns

Type mismatch for type Dictionary<String, Any> in JSON: Expected to decode Dictionary<String, Any> but found an array instead.

Can anyone advise? Thank you!!

1      

OK I missed the square brackets on this

    let AppGID = try JSONDecoder().decode([APIAppGAnalyticsID].self, from: dataAppGAnalyticsID)

1      

Glad you solved it, I would just give you a tip. Add this just above the let AppGID

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .formatted(formatter)

let AppGID = try JSONDecoder().decode([APIAppGAnalyticsID].self, from: dataAppGAnalyticsID)

Now you can change the struct to

struct Unknown: Codable {
  let id: String
  let name: String
  let date: Date
  let timestamped: Bool
  let dateStart: Date
  let dateEnd: Date
}

Which will give you dates to whatever locale is and remove the need for CodingKeys (This can be done in Ducky by Property Naming Style)

2      

Hacking with Swift is sponsored by Swiftsonic.

SPONSORED It's the final countdown! Swiftsonic is an all-new event for Swift developers taking place in Nashville, November 20–22. Build alongside fellow Swift and iOS developers with practical talks, the best in AI, fresh ideas, and conversations that make you pumped to ship again. So what are you waiting for? Get your pass and let’s dial the volume up to 11!

Learn more

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