Matteo Villa Matteo Villa - 2 months ago 14
JSON Question

Download and parse a JSON with swift

Can't figure out why this don't work...
when i run it, i have this error in the console:

[CONNECTION] OK, data correctly downloaded
[ERROR] An error has happened with parsing of json data
nil


maybe is the JSON format in the link that i pass in the
salvaJson()
function.

This is the viewController:

//MARK:proprietà
@IBOutlet weak var meteoLabel: UILabel!
@IBOutlet weak var descrizioneLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

let data = salvaJson()

let json = json_parseData(data!)

print(json)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


func salvaJson()->NSData?{
guard let url = NSURL(string: "http://www.medialweb.it/corsi_ok.json") else {
return nil
}
guard let data = NSData(contentsOfURL: url) else {
print("[ERROR] There is an unspecified error with the connection")
return nil
}
print("[CONNECTION] OK, data correctly downloaded")
return data
}


// funzione per la generazione del json a partire da un NSData
func json_parseData(data: NSData) -> NSDictionary? {
do {
let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
print("[JSON] OK!")
return (json as? NSDictionary)
} catch _ {
print("[ERROR] An error has happened with parsing of json data")
return nil
}
}


I have removed the comment at the top o JSON.
json_parseData()


Now print:[JSON] OK! but i still have
nil
instead of the printend json

Answer

Problem is your JSON cause json result must be start with array

I tested your code it is working code :

guard let url = NSURL(string: "http://pokeapi.co/api/v2/pokemon/1/") else {
            return nil
        } 

Pokemon Webapi and test your json format

UPDATE :

how can i print the error?

     do {
            let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
            print("[JSON] OK!")
            return (json as? NSDictionary)
        } catch {
            //print("[ERROR] An error has happened with parsing of json data")
            print("\(error)")
            return nil
        }