How to handle failure cases of JSON response using Codable? - ios

I have some JSON response, that I take from a server. In success case, it might be like:
{
"success": true,
"data": [
{
/// something here
}
]
}
If all server responses would be successful, it would be really easy to parse that JSON. But we have also failure cases like:
{
"success": false,
"msg": "Your session expired",
"end_session": true
}
That means we need to handle two cases. As you noticed, attributes like success, msg may occur in any response. In order to handle that, I created following struct:
struct RegularResponse<T: Codable>: Codable {
let success: Bool
let msg: String?
let endSession: Bool?
let data: T?
enum CodingKeys: String, CodingKey {
case success, msg, data
case endSession = "end_session"
}
}
It may contain some data if response is successfull or otherwise, it is possible to identify why the error occurred(using success attribute or msg). Parsing process would go like following:
let model = try JSONDecoder().decode(RegularResponse<MyModel>.self, from: data)
if model.success {
// do something with data
} else {
// handle error
}
Everything works fine, but what if following JSON comes as following:
{
"success": true,
"name": "Jon Snow",
"living_place": "Nights Watch",
//some other fields
}
Here, I don't have data attribute. It means, my RegularResponse cannot be parsed. So, the question is how to handle these kind of situations? My idea for solution is simple: always put data in success cases into data field on my API. By doing so, my RegularResponse will always work, no matter what is inside data. But, it requires changes on a server side. Can this be fixed in a client side, not changing a server side? In other words, how to handle above situation in Swift using Codable?

I'm not sure if this is the best solution but if you know that your error response is in that shape, i.e.:
{
"success": false,
"msg": "Some error",
"end_session": "true",
}
then you could make another Codable struct/class that follows this response.
struct ErrorResponse: Codable {
let success: Bool
let msg: String
let end_session: String
}
and then when you are responding to your JSON you could adjust your code to:
if let successResponse = try? JSONDecoder().decode(RegularResponse<MyModel>.self, from: data) {
//handle success
} else if let responseError = try? JSONDecoder().decode(ErrorResponse.self, from data) {
//handle your error
}

Related

Xcode, The given data was not valid JSON, Can't read the JSON from API properly

Hello I am creating an app with Xcode and I am having the following problem, I created this API (if you enter the link you'll see the JSON data) https://proyecto-idts6.epizy.com/models/getCategorias.php
If you dont want to enter the link here is how this si how the structure of the JSON looks like:
{
"items":[
{
"categorie":"Fruits",
"id_categorie":"1"
},
{
"categorie":"Animals",
"id_categorie":"2"
},
{
"categorie":"Juices",
"id_categorie":"3"
},
{
"categorie":"Vegetables",
"id_categorie":"4"
},
{
"categorie":"Alcohol",
"id_categorie":"5"
},
{
"categorie":"Desserts",
"id_categorie":"6"
}
]
}
The problem I have is that when I try to decode the data from the API it cant't be decoded properly, I am trying to recreate the same code of this youtube video, but with my API: https://www.youtube.com/watch?v=sqo844saoC4
What I want basically is to print the categories and storage each of them in variables (because i'll need to move the variables between screens)
This is how my code looks like:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://proyecto-idts6.epizy.com/models/getCategorias.php"
getData(from: url)
//Here is where i want to storage the variables from the JSON
}
private func getData(from url: String) {
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("something went wrong")
return
}
do {
let result = try JSONDecoder().decode([ResultItem].self, from: data)
print(result)
}
catch {
print("failed to convert\(error)")
}
})
task.resume()
}
}
struct Response: Codable {
let items: [ResultItem]
}
struct ResultItem: Codable {
let categorie: String
}
My goal is to have variables for example like this: categorie1=("the category 1 called from the JSON"), categorie2=("the category 2 called from the JSON"), categorie3=("the category 3 called from the JSON"),...
The problem is not in the decoding but in the remote API.
Your endpoint (https://proyecto-idts6.epizy.com/models/getCategorias.php) instead of returning a JSON is returning the following HTML
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("f5490e280a5e50f74932909856c3d3a3");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="https://proyecto-idts6.epizy.com/models/getCategorias.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
So you are trying to decode that HTML content, which clearly leads to the error your reported
failed to convertdataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

Populate model with API result

I am looking to populate my model with the "payload" section from my endpoint. I have created a model of DataResponse which has a record property of Payload. I would like to get only the data from the payload section of the API endpoint. My network call is incorrect and I must be structuring my models wrong, but I am not sure what needs to be fixed. I am not sure if it makes a difference but my endpoint was displaying as an XML and I converted it to JSON below.
struct DataResponse: Decodable {
let record: Payload
}
struct Payload: Decodable {
let SoldToday: Int
}
let url = URL(string: "https:------")!
URLSession.shared.dataTask(with: url) {data, response, error in
guard error == nil,
let data = data else {
print(error)
return
}
let dataResponse = try? JSONDecoder().decode(DataResponse.self, from: data)
if let dataResponse = dataResponse {
print(dataResponse.record.SoldToday)
}
}.resume()
These are the contents of my url endpoint:
{
"action": "API_DoQuery",
"errcode": "0",
"errtext": "No error",
"dbinfo": {
"name": "Daily",
"desc": []
},
"variables": {
"__iol": "&rand='+new Date().getTime())};\">",
"__script": "&rand='+new Date().getTime());void(0);",
"iol": "<img qbu='module' src='/i/clear2x2.gif' onload=\"javascript:if(typeof QBU=='undefined'){QBU={};$.getScript(gReqAppDBID+'?a=dbpage&pagename=",
"script": "javascript:$.getScript(gReqAppDBID+'?a=dbpage&pagename="
},
"chdbids": [],
"record": {
"payload": "{ \"RecordID\": 04-22-2022, \"SoldToday\": 18, \"ContractToday\": 869327, \"KWToday\": 160960 }",
"update_id": "1647544685640"
}
}
you need to fix 2 things to be able to decode your json data:
You need the models that match your json data. Such as:
struct DataResponse: Decodable {
let record: Record
}
struct Record: Decodable {
let payload: Payload
}
struct Payload: Decodable {
let SoldToday: Int
}
And you need to make sure your data is valid json. Currently variables is not valid, similarly for payload in record,
(it is enclosed in quotes). Once these are fixed, I was able to decode the data successfully in my tests.
Note that if your endpoint is giving you XML, then it is probably better to convert XML to your models directly, without having to convert to json. There are a number of XML parser libraries on github.

Swift dispatch queue block not running

I am currently writing an Alamofire HTTP request and am running into an issue where my view is not loading - likely because there is no data. The confusing part is that this was working yesterday. In the request I was able to do print(data) and the result was 506 bytes which, if my calculation is correct, is about the correct size given the JSON payload returned from the endpoint below.
#State var recipes = [Recipe]()
AF.request("http://localhost:3000/recipes").responseJSON { response in
guard let data = response.data else { return }
if let response = try? JSONDecoder().decode([Recipe].self, from: data) {
DispatchQueue.main.async {
self.recipes = response
}
return
}
}
I can confirm that the endpoint that is being hit returns the following data...
[
{
"name":"Manhattan",
"image":"https://images.unsplash.com/photo-1536935338788-846bb9981813?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2486&q=80",
"spirit":"Bourbon",
"ice":"Crushed",
"glass":"Coupe",
"yield":"3.75",
"description":"This is a good drink. You should make it.",
"ingredients":[
{
"bottle":"High West Son Of Bourye",
"amount":"2.5"
},
{
"bottle":"Cocchi Vermouth Di Torino",
"amount":"0.75"
},
{
"bottle":"Simple Syrup",
"amount":"0.083"
}
]
}
]
I also have my Recipe and Ingredient model here which should be able to decode based on the above JSON.
struct Recipe: Decodable, Identifiable {
var id = UUID()
var name: String
var image: String
var spirit: String
var ice: String
var glass: String
var yield: String
var description: String
var ingredients: [Ingredient]
}
struct Ingredient: Decodable, Identifiable {
var id = UUID()
var bottle: String
var amount: String
}
Is anybody able to spot an issue? I was trying to put a debugging print in the DispatchQueue but it is not printing which, to me, sounds like an error. However I am new to Swift/XCode/iOS and am not sure the best debugging practices for this.
If you can't debug yourself, NEVER USE try?. With more experience, I'd say that we tend to not use try?, but sometimes we do. But when we write try?, we are able to find an possible issue, ie debug if needed.
Let's do a proper try then, with a do/catch:
do {
let response = try JSONDecoder().decode([Recipe].self, from: data
DispatchQueue.main.async {
self.recipes = response
}
} catch {
print("Oops, there was en error while decoding: \(error)") // and not error.localizedDescription as it's more for users than developpers, so you'll skip all the useful informations
}
And read the output.
Going further?
Don't believe what's the API is supposed to return.
I've seen plenty and plenty of questions where the returned values was an error message, a XML Error message, a JSON Error message, an HTML Error message, and a JSON value missing, or of bad type, etc. And that, your JSONDecoder wasn't expecting it...
Reasons could be various, from bad/missing parameters, bad/missing APIKey, server down, bad/missing header, etc.
But, then, print the returned value.
print(String(data: data, encoding: .utf8) ?? "No data found")
So print it directly when you get it, or at least in the catch:
} catch {
print("Oops, there was en error while decoding: \(error)") // and not error.localizedDescription as it's more for users than developpers, so you'll skip all the useful informations
print("While getting response stringified: \(String(data: data, encoding: .utf8) ?? "No data found")")
}
If you don't understand the error message output, it's okay, there is no shame about it. But your first job is to get that error message. You can share it on SO if you don't understand it, you might get help with that. But currently, we can't guess what's wrong with your code.
It's a good idea to drop some clues in your code when looking for a failure.
If it were me I'd do something like this:
AF.request("http://localhost:3000/recipes").responseJSON { response in
guard let data = response.data else {
print("Error trying to receive data in ", #file, #function)
return
}
do {
let response = try JSONDecoder().decode([Recipe].self, from: data) {
DispatchQueue.main.async {
self.recipes = response
}
} catch {
print("Error failed to decode json data with error: \(error) in \(#file)", #function)
}
}

Could not cast NSDicationry with NSData in WebService call request

Trying to wrap Codable response data from WebService
used cocoa pod
pod 'WebService', '~> 0.4'
var webServiceObject : WebService = WebService()
webServiceObject.sendRequest(URLString, parameters: parameters as NSDictionary?, requestType: .post, success: {response,data in
do{
// Handle data when request Success
let jsonDecoder = JSONDecoder()
do {
let result = try jsonDecoder.decode([ResponseModelValue].self, from: data as! Data)
print(response?.statusCode as Any)
print("Success Response Value", result)
}
} catch {
print(error)
}
}, failed: {
(response : HTTPURLResponse?, ResponseDict : Any?) in
print(response?.statusCode as Any)
print("Failed Response Dictionary", ResponseDict!)
// Handle data when request fails
}, encoded: false )
I got following error
Could not cast value of type '__NSDictionaryI' (0x10c81ab38) to 'NSData' (0x10c819620).
Can any one suggest me what I done wrong here, so I can parse proper response data with codable [ResponseModelValue]
After looking at that library, it appears that it will turn the response into a dictionary if possible and fall back to returning data.
https://github.com/kansaraprateek/WebService/blob/master/WebService/Classes/WebService.swift#L281
It doesn't appear like there is a way to configure that behaviour. The library was also created before Codable was created. You may need to reach out the library owner for a fix, fork the repo and fix it yourself, or switch to using URLSession since the code you posted is mostly the same as a URLSession call.

Can I use SwiftyJSON to get at error contents in Siesta?

I'm writing a test for my Siesta-based class, and I'm trying to access the error I received from the server. In my object, I configured the service like so:
self.service.configure {
$0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
// other configuration setup
}
My test contains the following:
api.fetchApiToken(libraryRequiringAuth).onSuccess({ _ in
// Then
XCTFail("Expected request failure, got success")
}).onFailure({ [weak self] (error) in
XCTAssertEqual(error.httpStatusCode, expectedStatusCode)
let serverError: JSON? = error.entity?.typedContent()
XCTAssertEqual(serverError![0]["title"].string, expectedErrorMessage)
print("Expected error is: \(error)")
XCTAssertNil(self?.api.bearerAuthHeader)
expectation.fulfill()
})
The line let serverError: JSON? = error.entity?.typedContent() is setting serverError to nil, but in the debugger, I can see that error.entity exists and has the content I expect. Can I not use SwiftyJSON at this point?
Edit:
Here are the contents of the error:
Error Error(userMessage: "Forbidden", httpStatusCode: Optional(403), entity: Optional(Siesta.Entity(content: [{
ipRangeError = {
libraryId = 657;
libraryName = "Test library";
requestIp = "my.ip.address.was_here";
};
status = 403;
title = "Authentication Failed";
userData = {
};
}], charset: Optional("utf-8"), headers: ["content-type": "application/json; charset=utf-8"], timestamp: 490978565.82571602)), cause: nil, timestamp: 490978565.825499)
It looks like your SwiftyJSONTransformer is leaving errors untouched. Try configuring it with transformErrors: true:
private let SwiftyJSONTransformer =
ResponseContentTransformer(transformErrors: true)
{ JSON($0.content as AnyObject) }
Without that flag, the error entity is still an NSDictionary instead of a SwiftyJSON JSON, and typedContent() sees those as mismatched types and gives you a nil.
(And to the question in the title: yes, you can get the full error content, as well as response headers and any underlying ErrorType / NSError info from the underlying networking layer.)

Resources