I have old code from team where they were failing to parse Bool response.
NetworkManager.shared().executeWith(request: APIRouter.firebasetoken(param)) { (httpResponse, jsonData, error) in
if httpResponse?.statusCode == 200 {
guard let json = jsonData else {return}
if let isSuccess = json.bool, isSuccess == true{
print("Success to send fcm token")
}
}else{
print("failed to send fcm token", error?.localizedDescription)
}
}
The issue I am facing here is that the response is strictly coming as bool either true
or false
as attached image of postman.
I am getting success code 200, but jsonData
is always nil.
So please help me to parse the Bool response.
I can’t change the code, as they have base class for all these, so only change I have to apply is in this method only.
Any help will be appreciated.
2
Answers
Alright, I cannot make a concrete-accurate guess with this limited information but, it seems like the response might be malformed. Which I mean by saying malformed is that, there could be an issue with the way the server is generating the response.
You mentioned that the response code is 200 which is cool, but
jsonData
isnil
which is bad, and the response is aboolean
which is weird. With the limited information you provided, my best guess is that the response is not a JSON object.In order to handle this situation (if thats the case), you can handle the plain text response by updating your code:
You can also check if the server is setting the
Content-Type
header correctly. It should be set toapplication/json
to indicate that the response is in JSON format. But I don’t have the best knowledge on that.We can understand your issue with additional information. Please correct me if I got your problem wrong. Hope we can solve it.
Without knowing how you get
jsonData
in(httpResponse, jsonData, error)
, it’s hard to tell what’s wrong.But, if we use
let data = Data("true".utf8)
, having a only a boolean as JSON is valid, a little strange (ie uncommon), but valid JSON.But to be able to parse it, we need to add some options to
JSONSerialization
.You need to use
.fragmentsAllowed
that should allowString
,Number
,Bool
as top level and not onlyArray
/Dictionary
(ie "list" or "objects").You can also directly use
Codable
:Seeing
.stringValue
,.bool
I suspect you use SwiftyJSON (or assimilated), I strongly suggest to useCodable
if possible.Side note, in the encoding (and so maybe in the decoding at some point), there could be limitation due to iOS versions, see related question