Search code examples
jsonswiftalamofirecodablejsondecoder

Present results with alamofire/Swift


My JSON

When I try to present the results I received this message "Response could not be decoded because of error: The data couldn’t be read because it isn’t in the correct format."

This is my format and its right I think.

  import Foundation

// MARK: - Response
struct Response: Codable {
    let code: Int
    let meta: Meta
    let data: [Datum]
}

// MARK: - Datum
struct Datum: Codable {
    let id, userID: Int
    let title, body: String

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case title, body
    }
}

// MARK: - Meta
struct Meta: Codable {
    let pagination: Pagination
}

// MARK: - Pagination
struct Pagination: Codable {
    let total, pages, page, limit: Int
}

also I try with this code to view the result.

private func fetchData() {
        self.task = AF.request(self.baseUrl, method: .get, parameters: nil)
        .publishDecodable(type: [Response].self)
            .sink(receiveCompletion: {(completion) in
                switch completion {
                case .finished:
                    ()
                case .failure(let error):
                    print(String(describing: error))
                    //print(error.localizedDescription)
                }
            }, receiveValue: {[weak self ](response) in
                switch response.result {
                case .success(let model):                self?.presenters = model.map {PostPresenter(with: $0)}
                case.failure(let error):
                     print(String(describing: error))
                    //  print(error.localizedDescription)
                }
            })
    }

And my post presenter code is this

struct PostPresenter: Identifiable {
    
    let id = UUID()
    let title: String
    
    init(with model:Response) {
        self.title = model.data
        
    }
    
}

Solution

  • Two mistakes

    1. The root object is a dictionary so it's (type: Response.self)

    2. and model.data is [Datum] so declare

      struct PostPresenter: Identifiable {
      
          let id = UUID()
          let data: [Datum]
      
          init(with response: Response) {
              self.data = response.data
          }
      }
      

    And in a Codable context print the error always print(error), not print(String(describing: error)) and never print(error.localizedDescription)