I am working on an app for iOS and I'm using Swift 4 to develop it. The app will make use of REST calls to populate pickers and tables. The code below has been used to work on calls successfully, however now, I don't receive any data. The REST has been tested with postman which gives me the expected results.
typealias JSONCompletionHandler = (Data?, Int?, Error?) -> void
static function getData(completionHandler: @escaping JSONCompletionHandler){
let url = URL(string: "http://apiurl.com")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
let htttResponse = response as? HTTPURLResponse
completeionHandler(data, httResponse?,statuscode, error)
}
task.resume()
}
EDIT
Below is the printout of the HTTPURLResponse
Headers {
"Cache-Control" = (
"no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
);
Connection = (
"Keep-Alive"
);
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Tue, 01 May 2018 15:44:27 GMT"
);
Expires = (
"Thu, 19 Nov 1981 08:52:00 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Pragma = (
"no-cache"
);
Server = (
"Apache/2.2.29 (Win32) mod_ssl/2.2.29 OpenSSL/0.9.8zf"
);
"Set-Cookie" = (
"ZDEDebuggerPresent=php,phtml,php3; path=/"
);
"Transfer-Encoding" = (
Identity
);
"X-Powered-By" = (
"ZendServer 8.0.2"
);
} }
apache connection log
Application
- [02/May/2018:09:51:04 +0100] "GET /public/rest/catalogue-standard-fit/ HTTP/1.1" 200 15669
- [02/May/2018:09:51:04 +0100] "GET /public/rest/catalogue-multi-fit/ HTTP/1.1" 200 14302
- [02/May/2018:09:51:04 +0100] "GET /public/rest/catalogue-accessory/ HTTP/1.1" 200 216
POSTMAN
10.2.13.221 - - [02/May/2018:09:52:55 +0100] "GET /public/rest/catalogue-accessory/ HTTP/1.1" 200 216
EDIT
The data is being returned and the issue is with the method used to parse the JSON data.
I'm using the Codable approach available in swift 4 and the structures used are below along with the how the JSON data output is (from postman)
//Structures for JSON
struct PartType: Codable {
let id: String
let name: String
}
struct Availability: Codable {
let id: String
let status: String
}
struct AccessorySearch: Codable {
let part_type = [PartType]()
let availability = [Availability]()
}
JSON data from POSTMAN
{
"part_type": [
{
"id": "1",
"name": "Type 1"
},
{
"id": "2",
"name": "Type 2"
},
{
"id": "3",
"name": "Type 3"
}
],
"availability": [
{
"id": "1",
"status": "In Stock"
},
{
"id": "2",
"status": "In Development"
},
{
"id": "3",
"status": "Not in Stock"
}
]
}
Method used
private func jsonDecodeString(data: Data?) {
// array of the above structures
paryTypeArrayStructure.insert(PartType(id: "0", name: "Select Option"), at: 0)
availabilityArrayStructure.insert(Availability(id: "0", status: "Select Option"), at: 0)
let decoder = JSONDecoder()
do {
let decodeAccessories = try decoder.decode(AccessorySearch.self, from: data!)
print("PART TYPE: ",decodeAccessories.part_type)
print("AVAILABILITY: ",decodeAccessories.availability)
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
print(json)
for item in decodeAccessories.availability {
print(item)
availabilityArrayStructure.append(item)
}
for item in decodeAccessories.part_type {
paryTypeArrayStructure.append(item)
}
//print(availabilityArrayStructure)
} catch let jsonErr {
print ("Failed to decode: ", jsonErr)
displayErrorMessage(message: "[RCCA003 JSONException occurred when reading the response from server]")
}
}
I tried JSONSerilization and was able to parse the data. So now my question is, why did my initial attempt parsing fail? I apologise for any confusion, you've all been very helpful, so thank you.
EDIT - Solution found...but why did it work?
Firstly I want to say thanks to all those commenting and providing areas for research. It turns out the issue with the JSON parsing and how I setup up the structures.
//Structures for JSON
struct PartType: Codable {
let id: String?
let name: String?
}
struct Availability: Codable {
let id: String?
let status: String?
}
struct AccessorySearch: Codable {
let part_type: [PartType]
let availability: [Availability]
}
The structures that will parse the part_type arrays and availability arrays have their variables set to optional. This allowed the JSON to be parsed. Can anyone shed some light on this? Why did this simple change work? Thanks again.