I have an api which return a JSON and i want to parse this JSON and use it in my application.
I have tried the get method from this: swift JSON login REST with post and get response example
Code:
func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "my link"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /public/api/services")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo
// let's just print it to prove we can access it
print("The todo is: " + todo.description)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
guard let todoTitle = todo["name"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
And i got as an output: error trying to convert data to JSON..
My JSON IS:
[
{
"id": 1,
"name": "Services 1",
"description": "This is a description of Services 1. This is a description of Services 1 This is a description of Services 1. ",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"name": "Services 2",
"description": "This is a description of Services 2. This is a description of Services 2 This is a description of Services 2. ",
"created_at": null,
"updated_at": null
}
]
Why i got error parsing the JSON?
Also, how to loop for the array and print each item?
For example:
service 1 description is: This is a description of Services 1. This is a description of Services 1 This is a description of Services 1.
service 2 description is: This is a description of Services 2. This is a description of Services 2 This is a description of Services 2.