Search code examples
swiftxcodehttpsession

Swift HttpSession decode arrays


I have a code to send post requests to a NestJS api. It works, but there's a request that returns the following json: (Multiplied the entrires to help understand the context)

[
    {
        "friendshipid": "64ad04f03e3afbddb87f2c82",
        "userid": "64ad04c53e3afbddb87f2c26",
        "username": "Alms2",
        "pfp": "http://localhost:3000/CDN//pfp/default.png"
    },
    {
        "friendshipid": "64ad04f03e3afbddb87f2c82",
        "userid": "64ad04c53e3afbddb87f2c26",
        "username": "Alms2",
        "pfp": "http://localhost:3000/CDN//pfp/default.png"
    }
]

How can i recognise it in my code? Thanks!

HttpPOST.swift

import Foundation
func apiCall<T: Decodable>(urlString: String, body: [String:AnyHashable]) async throws -> T {
    
    guard let url = URL(string: "http://192.168.1.71:3000/\(urlString)") else { throw URLError(.badURL) }
    
    var request = URLRequest(url: url)
    // method, body, headers
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONSerialization.data(withJSONObject: body)
    
    // make rqs
    let (data, _) = try await URLSession.shared.data(for: request)
    return try JSONDecoder().decode(T.self, from: data)
}

struct IsLoggedIn: Decodable {
    var loggedin: Bool
}

struct UserData: Decodable {
    var username: String;
    var userid: String;
    var pfp: String;
}

struct Friends: Decodable {
 // how to recognise???
}

Solution

  • Remove:

    struct Friends: Decodable {
     // how to recognise???
    }
    

    Change and add:

    return try JSON Decoder().decode([T].self, from: data)
    

    Also, you forgot to add friendshipid. And no need for ";" in the end.

    struct UserData: Decodable {
      var username: String
      var userid: String
      var pfp: String
      var friendshipid: String
    }
    

    T means 1 element {element} and [T] means many elements {element1, element2}