Search code examples
swiftapihttprequesturlsession

The data returned from the api is always nil?


I'm retrieving data from an API. The problem is the data always returns as nil. It is a list of questions, usually 10. The code I wrote always returns 10 nil results. I tried the same code with different APIs with the same structure and it always works.

This is the struct:

struct Questions: Codable{
    let question: String?
}

This is the code:

guard let url = URL(string: "http://adminsapi.somee.com/Api/Test/?id=1") else { return }
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        do{
            let test = try? JSONDecoder().decode([Questions].self, from: data)
            for ask in test{
                print(ask.question)
            }
        }
    }.resume()

This is the result I get:

nil nil nil nil nil nil nil nil nil nil

This is the data returned from the API in postman:

[
    {
        "AskName": "Urgenct of defecation"
    },
    {
        "AskName": "Mucous and streaked stools"
    },
    {
        "AskName": "vomiting"
    },
    {
        "AskName": "Fever"
    },
    {
        "AskName": "Tympany on percussion"
    },
    {
        "AskName": "Bowel sounds"
    },
    {
        "AskName": "shifting dullness"
    },
    {
        "AskName": "psoas and obturator sign"
    },
    {
        "AskName": "rebound tenderness"
    },
    {
        "AskName": "signs of shock"
    }
]

Also, when I try to parse the json and read the whole data in one string, it works completely fine. I don't know where the problem is.


Solution

  • Your Question implementation is wrong. You need to tell the compiler that the question variable needs to be decoded using the AskName key.

    struct Questions: Codable {
        let question: String?
    
        private enum CodingKeys: String, CodingKey {
            case question = "AskName"
        }
    }