How to change error.localizedDescription to JSON by Swift?

Advertisements

In Swift I got the error from Cloud Functions.
And I caught the error like this

functions.httpsCallable("addMessage").call(["text": inputField.text]) { result, error in
  if let error = error as NSError? {
    if error.domain == FunctionsErrorDomain {
      let code = FunctionsErrorCode(rawValue: error.code)
      let message = error.localizedDescription
      let details = error.userInfo[FunctionsErrorDetailsKey]
    }
  }
}

The message get like JSON format from Cloud functions.
{"message":"text is required","status":"INVALID_ARGUMENT"}

If I got the error message from Cloud functions, and I want to display to the user.
First I tried
let status = message["status"]
But I got No exact matches in call to subscript in xcode.
How do I resolve this problem?

>Solution :

error.localizedDescription is obviously a JSON string, you have to deserialize it

let messageJSON = error.localizedDescription
let messageDictionary = try? JSONDecoder().decode([String:String].self, from: Data(messageJSON.utf8))
let message = messageDictionary?["message"] ?? ""

Leave a Reply Cancel reply