-1

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???
}
Noel
  • 35
  • 6

1 Answers1

-1

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}

  • [T] is not needed, see my comment above. And you don’t need to decode every field in a json dictionary. – Joakim Danielson Jul 31 '23 at 16:59
  • Its working, but can you help me, how to store the response in a variable? I get a response like this: ```[Chatenium.FriendData(username: "Alms2", userid: "64ad04c53e3afbddb87f2c26", pfp: "http://localhost:3000/CDN//pfp/default.png", friendshipid: "64ad04f03e3afbddb87f2c82")]``` – Noel Jul 31 '23 at 19:31
  • Looks like your response is an array with 1 element, so you can store this into a variable as `let user = response.first` or `let user = response[0]` – Vali Zairov Aug 15 '23 at 07:25