[Solved] Why does my JSON request fail more than 50% of the time? [closed]


There is not enough information to debug this specific problem but it is likely that the JSON response you are receiving has optional fields. Fields that are expected to be empty for certain responses. This part of your code,

  if
    let dictionary = jsonData as? [String: Any],
    let results = dictionary["results"] as? [[String: Any]],
    !results.isEmpty,
    case var result = results[0],
    let lexicalEntries = result["lexicalEntries"] as? [[String: Any]],
    !lexicalEntries.isEmpty,
    case var lexicalEntry = lexicalEntries[0],
    let derivatives = lexicalEntry["derivatives"] as? [[String:Any]],
    !derivatives.isEmpty,
    case var derivative = derivatives[0],
    let pronunciations = lexicalEntry["pronunciations"] as? [[String: Any]],
    !pronunciations.isEmpty, case var pronunciation = pronunciations[0],
    let entries = lexicalEntry["entries"] as? [[String:Any]],
    !entries.isEmpty,
    case var entry = entries[0],
    let senses = entry["senses"] as? [[String:Any]],
    !senses.isEmpty, case var sense = senses[0],
    let examples = sense["examples"] as? [[String:Any]],
    !examples.isEmpty,
    case var example = examples[0]
    //Now I pick out details from the JSON like audio, sample sentence, etc.
  {

needs to be split to handle (and report) missing fields. That is 20 boolean tests that all must pass before your ‘good’ path executes. What is likely happening is that your dictionary accesses are failing. If for instance dictionary does not contain “lexicalEntries”, then that will take the failure path and not return an empty array as you are expecting.

Confirm that the same words fail every time. Look at the actual JSON for failed words and make sure that every field is being reported.

UPDATE:

if let response = response,
  let data = data,
  let jsonData = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
{
  guard let dictionary = jsonData as? [String: Any] else {
    print("Error: dictionary was not returned by endpoint")
    return
  }
  guard let results = dictionary["results"] as? [[String: Any]] else {
    print("Error: no results array returned by endpoint")
    return
  }
  result = results.first
  ...

1

solved Why does my JSON request fail more than 50% of the time? [closed]