saqib
saqib

Reputation: 13

I am try to fetch the data from sql server through WCF service

import UIKit

public struct student: Decodable {
    let id:Int
    let name:String
}

class ViewController: UIViewController {

    @IBAction func btnshow(_ sender: Any) {

        let link = "http://10.211.55.3/WcfService1/Service1.svc/GetData"
        guard let url = URL(string: link)else{
            print("error during connection")
            return
        }
        URLSession.shared.dataTask(with: url) { (data, response, error) in

            guard let data = data
                else{                    print("there is no data")
                return
            }
            do{
                let students = try JSONDecoder().decode(student.self, from: data)
                print(students)


            } catch{
                print("conversion error")
                print(error)
            }
        }.resume()            
    }
}

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))

Upvotes: 1

Views: 122

Answers (1)

Adam
Adam

Reputation: 4828

Well, the error printed out is pretty self explanatory. The data you got is not formatted the way you're expecting it and some keys are missing (the id key) so JSONDecoder() can't decode it.

Make sure that the response you got is properly formatted before trying to decode it.

EDIT: So after seeing your comment, your model doesn't match the JSON you're receiving, it should be something like this :

import UIKit

public struct JsonStudent: Decodable {
    let students: [Student]

    enum CodingKeys: String, CodingKey {
        case students = "GetDataResult"
    }
}

public struct Student: Decodable {
    let id: Int
    let name: String
}

class ViewController: UIViewController {

    @IBAction func btnshow(_ sender: Any) {
        let link = "http://10.211.55.3/WcfService1/Service1.svc/GetData"

    guard let url = URL(string: link) else {
            print("error during connection")
            return
    }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data
                else {                    print("there is no data")
                return
            }
            do {
                let students = try JSONDecoder().decode(JsonStudent.self, from: data)
                print(students)
            } catch {
                print("conversion error")
                print(error)
            }
        }.resume()            
    }
}

Upvotes: 0

Related Questions