Search code examples
swiftcodablejsondecoderjsonencoder

Swift used Codable, but the type is not correct


I know that Codable = Decodable & Encodable but when calling json from xcode,

Codable was given as a struct, but an error saying

Argument type'login.Type' does not conform to expected type'Encodable' appears.

json code

struct login: Codable {
    var userId: String?
    var userPw: String?
class func LoginBoard(_ completeHandler: @escaping (login) -> Void) {
            
    let loginboard: String = MAIN_URL + "/member/login"
    guard let url = URL(string: loginboard) else {
      print("Error: cannot create URL")
        return
    }
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"
    urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
    urlRequest.httpBody = try? JSONEncoder().encode(login) // ERROR [Argument type 'login.Type' does not conform to expected type 'Encodable']
            
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) in
        guard error == nil else {
        print("error calling Post on /todos/1")
         print(error!)
           return
        }

        guard let responseData = data else {
        print("Error: did not receive data")
          return
        }

        do {
            let decoder = JSONDecoder.init()
            let LoginList = try decoder.decode(login.self, from: responseData)
            completeHandler(LoginList)
        }
        catch {
            print("error trying to convert data to JSON")
            return
        }
    }
    task.resume()
}

There is no error in try decoder.decode

but only in urlRequest.httpBody = try? JSONEncoder().encode(login) what is the problem?


Solution

  • You need to have something like this to set the values.

    let loginvalues = login(userId: "john", userPw: "adfadfa")
    
    urlRequest.httpBody = try? JSONEncoder().encode(loginvalues)
    

    If you place this inside a play ground and run it you will see that you get the json data.

    struct Login: Codable {
        var userId: String?
        var userPw: String?
    }
    
    let loginvalues = Login(userId: "john", userPw: "adfadfa")
    
    let test = try? JSONEncoder().encode(loginvalues)
    print(String(data: test!, encoding: .utf8)!)