Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with parsing JSON file

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading