Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can not figure out why this doesn't work. On the internet I found a lot of solutions with local json(not api) or with api without apiKey which in my case must be in the header(tested in Postman).

struct Categories: Decodable {
        let name: String
        let id: Int
    }
    
    class ViewController: UIViewController {
        
        
        let api_key = "..."
        
        let urlString = "..."

        override func viewDidLoad() {
            super.viewDidLoad()
            
            let url = URL(string: urlString)
            
            var request = URLRequest(url: url!)
            
            request.addValue(api_key, forHTTPHeaderField: "user-key")
            request.httpMethod = "GET"
            
            URLSession.shared.dataTask(with: request) { data, response, error in
                if let data = data {
                    if let category = try? JSONDecoder().decode(Categories.self, from: data) {
                            print(category.name)
                        return
                    }
                }
                
                print("Fetch failed: (error?.localizedDescription ?? "Unknown error")")
            }.resume()
        }
    }

I removed the urlString and api_key from the code above, but I am sure they are ok because I tested them in Postman
Problem - always getting printed Fetch failed: Unknown error
Here is how my json looks like:

{
    "categories": [
        {
            "categories": {
                "id": 1,
                "name": "A"
            }
        },
        {
            "categories": {
                "id": 2,
                "name": "B"
            }
        }....
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
216 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead of just categories struct ... you should have these structs

// MARK: - Category
struct Category: Codable {
    let categories: [CategoryElement]
}

// MARK: - CategoryElement
struct CategoryElement: Codable {
    let categories: Categories
}

// MARK: - Categories
struct Categories: Codable {
    let id: Int
    let name: String
}




URLSession.shared.dataTask(with: request) { data, response, error in
    if let data = data {
        do {
            // process data
            if let category = try JSONDecoder().decode(Category.self, from: data) { print(category) }
        } catch  {
            print(error)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...