alexbredikin
alexbredikin

Reputation: 133

In Swift, check if a key exists in JSON

I have the following function. It is supposed to take the current song playing information from the API webpage. When a song is playing, the page says:

{ "artist" : "Artist", "song" : "Song" }

When no data is available (No song is playing):

{ "error" : "no song metadata provided" }

Is there a way to check if the "error" key exists? Or what can I do with this issue?

func songNowPlaying() {
    let endpoint = NSURL(string: "http://api.vicradio.org/songs/current")
    let jsonData = NSData(contentsOfURL: endpoint!)

    do {
        let parsed = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableArray
        SongNowText.text = parsed.valueForKey("song").componentsJoinedByString("")
        ArtistNowText.text = parsed.valueForKey("artist").componentsJoinedByString("")
    }
    catch let error as NSError {
        print("\(error)")
    }
}

Upvotes: 3

Views: 6180

Answers (1)

vadian
vadian

Reputation: 285072

The URL returns a JSON dictionary not an array. You can check for both cases this way

func songNowPlaying() {
  let endpoint = NSURL(string: "http://api.vicradio.org/songs/current")
  if let jsonData = NSData(contentsOfURL: endpoint!) {

    do {
      let parsed = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as! [String:String]
      if let error = parsed["error"] {
        print("Result error: \(error)")
      } else {
        if let song = parsed["song"] { 
          SongNowText.text = song 
        }
        if let artist = parsed["artist"] { 
          ArtistNowText.text = artist
        }
      }
    }
    catch let error as NSError {
      print("Serialization error: \(error)")
    }
  }
}

as the JSON object can be downcasted to [String:String] any further downcasting is not needed.

Upvotes: 4

Related Questions