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

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.