英文:
How to change error.localizedDescription to JSON by Swift?
问题
在Swift中,我从云函数中收到了错误。我像这样捕获了错误:
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]
}
}
}
消息以JSON格式从云函数获取,如下所示:
{"message":"text is required","status":"INVALID_ARGUMENT"}
如果我从云函数收到错误消息,而我想要将其显示给用户。首先,我尝试了以下代码:
let status = message["status"]
但在Xcode中我收到了 No exact matches in call to subscript
的错误消息。我该如何解决这个问题?
英文:
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?
答案1
得分: 2
error.localizedDescription
显然是一个 JSON 字符串,你需要对其进行反序列化。
let messageJSON = error.localizedDescription
let messageDictionary = try? JSONDecoder().decode([String: String].self, from: Data(messageJSON.utf8))
let message = messageDictionary?["message"] ?? ""
英文:
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"] ?? ""
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论