Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

ios - Unable to decode with Swift decodable

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

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

1 Reply

0 votes
by (71.8m points)

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)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...