I am trying to parse a JSON file from a PHP web page on my website using Swift, i get the error "Cannot find ‘allnames’ in scope" on Xcode.
Please find here my code for Swift :
let serviceUrl = "http://***"
let url = URL(string: serviceUrl)!
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url){ (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
let decoder = JSONDecoder()
do{
let allnames = try decoder.decode(Entry.self, from: data!)
}catch{
print("Error in JSON parsing")
}
print(allnames)
}
}
dataTask.resume()
}
Thank you for your answers !
>Solution :
your variable allnames is out of scope, you have to declare it outside.
change the declaration like me,
let serviceUrl = "http://***"
let url = URL(string: serviceUrl)!
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url){ (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
let allnames = []
let decoder = JSONDecoder()
do{
allnames = try decoder.decode(Entry.self, from: data!)
}catch{
print("Error in JSON parsing")
}
print(allnames)
}
}
dataTask.resume()
}