yesman yesman - 6 months ago 19
JSON Question

Swift : football-data API doesn't work

I'm trying to use football-data.org api. I wrote some code same with before I did sample. But this api is using token and I didn't figured out how to add and do that.

I did these code and nothing happens :

func getData(){
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/fixtures"))
url.addValue("my token is here", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"

let task = NSURLSession.sharedSession().dataTaskWithRequest(url) { (data, response, error) in
self.setLabels(data!)
}

task.resume()
}

func setLabels(MatchData: NSData){
//var jsonError: NSError?

do{
let json = try NSJSONSerialization.JSONObjectWithData(MatchData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

if let sys = json["soccerseason"] as? NSDictionary{
if (sys["href"] as? String) != nil{
let seasonsUrl = sys["href"] as! String

print(seasonsUrl)
}


}
}
catch{
//error

}
}


I'm not getting value or something. I'm new with json. What's wrong in my code?

Answer

"soccerseason" is in "_links", like this:

if let links = json["_links"] as? [String:AnyObject],
    sys = links["soccerseason"] as? [String:String],
    seasonsUrl = sys["href"] {
        print(seasonsUrl)
}

This is for the main one.

I've also noticed there's one (the same one, actually) in each dictionary in the main array:

if let fixtures = json["fixtures"] as? [[String:AnyObject]] {
    for fixture in fixtures {
        if let links = fixture["_links"] as? [String:AnyObject],
            sys = links["soccerseason"] as? [String:String],
            seasonsUrl = sys["href"] {
            print(seasonsUrl)
        }
    }
}

The URLs are in the _links part in each dictionary in the fixtures array:

if let fixtures = json["fixtures"] as? [[String:AnyObject]] {
    for fixture in fixtures {
        if let links = fixture["_links"] as? [String:[String:String]],
            season = links["soccerseason"],
            seasonsUrl = season["href"],
            awayTeam = links["awayTeam"],
            awayTeamUrl = awayTeam["href"] {

                print(seasonsUrl)
                print(awayTeamUrl)
        }
    }
}

And awayTeamName and homeTeamName are at the same level than _links inside the array of dictionaries:

if let fixtures = json["fixtures"] as? [[String:AnyObject]] {
    for fixture in fixtures {
        if let awayTeamName = fixture["awayTeamName"] as? String,
            homeTeamName = fixture["homeTeamName"] as? String {

            print(awayTeamName)
            print(homeTeamName)
        }
    }
}