How do I assign a variable to the definitions in JSON?

Hello,

I am successfully using the following code to play the audio from the JSON. Now I want to assign a definition (any one of them) to a string. How do I pull the definition from the JSON?

func speakRandomWord() {

 selectRandomWord()
    appId = "secret"
   appKey = "secret"
   language = "en"
   word = randomWord //getting random word from another service
   regions = "us"
   word_id = word.lowercased() //word id is case sensitive and lowercase is required
   url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/entries/\(language)/\(word_id)/regions=\(regions)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")

let session = URLSession.shared
_ = session.dataTask(with: request, completionHandler: { data, response, error in
    if let response = response,
        let data = data,
        let jsonData = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject] {

if let dictionary = jsonData as? [String: Any],
let results = dictionary["results"] as? [[String: Any]],
//You need to choose one from "results"
!results.isEmpty, case let result = results[0],
let lexicalEntries = result["lexicalEntries"] as? [[String: Any]],
//You need to choose one from "lexicalEntries"
!lexicalEntries.isEmpty, case let lexicalEntry = lexicalEntries[0],
let pronunciations = lexicalEntry["pronunciations"] as? [[String: Any]],
//You need to choose one from "lexicalEntries"
!pronunciations.isEmpty, case let pronunciation = pronunciations[0]
//This is where I am stuck.  How do I proceed?

{
//Here you can use `pronunciation` as a Dictionary containing "audioFile" 
if let audioPath = pronunciation["audioFile"] as? String {
    print("This is \(audioPath)")

let path = String(describing:audioPath)
let url = URL.init(string: path)
self.player = AVPlayer.init(url: url!)
self.player.play()

}
else {
    print ("No data for this word")
    self.speakRandomWord()
    }
}

    } else {
        print(error)
        print(NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue))
        print("Failed to load: \(error?.localizedDescription)")
        self.speakRandomWord()
    }
}).resume()

}

Best Answer

Answers

Sign In or Register to comment.