我试图使用football-data.org api。在我做样本之前,我写了一些相同的代码。但是这个api正在使用令牌,我没有想出如何添加和执行此操作。
我做了这些代码而没有任何反应:
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
}
}
我没有获得价值或其他东西。我是json的新人。我的代码有什么问题?
答案 0 :(得分:1)
"soccerseason"
位于"_links"
,如下所示:
if let links = json["_links"] as? [String:AnyObject],
sys = links["soccerseason"] as? [String:String],
seasonsUrl = sys["href"] {
print(seasonsUrl)
}
这是主要的。
我还注意到主阵列中每个字典中都有一个(实际上是同一个):
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)
}
}
}
网址位于_links
数组中每个字典的fixtures
部分:
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)
}
}
}
awayTeamName
和homeTeamName
与词典数组中的_links
处于同一级别:
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)
}
}
}