I am taking an array of urls and decoding them within a Collection View. I have completed this successfully before but am receiving an error this time around.
I am receiving the error:
Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))
What I am noticing is that it seems to be attempting to decode one before completing the other, if possible. I believe this because some of the times that I run the app it will print one or two instances of the decoded data fine before throwing the error.
Here is my Code:
struct Details: Codable {
let name: String
let location: Location
}
struct Location: Codable {
let address: Address
let geoCode: Geo
}
struct Geo: Codable {
let latitude: String
let longitude: String
}
struct Address: Codable {
let street: String
let state: String
let city: String
let postalCode: String
let country: String
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = showtimesCollection.dequeueReusableCell(withReuseIdentifier: "timeCell", for: indexPath) as! TimeCell
let theaters = self.theaterIds[indexPath.row]
let id = theaters
let apiKey = ""
let url = URL(string: "http://data.tmsapi.com/v1.1/theatres/\(id)?api_key=\(apiKey)")
print(url!)
let request = URLRequest(
url: url! as URL,
cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
timeoutInterval: 10 )
let session = URLSession (
configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: OperationQueue.main
)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
do { let theater = try JSONDecoder().decode(Details.self, from: data) //error: Swift.DecodingError.dataCorrupted
print(theater)
} catch let err {
print("JSON Error")
}
})
task.resume()
return cell }
The Array looks like this:
["12345", "23456", "34567", "45678"]
The array is printing correctly to the console and so are the urls being decoded. They appear the same way as one the controller that this worked successfully.
The JSON looks like this:
{
"theatreId": "2469",
"name": "Paramount Theatre",
"location": {
"telephone": "512-472-5470",
"geoCode": {
"latitude": "30.2694",
"longitude": "-97.7419"
},
"address": {
"street": "713 Congress Ave",
"state": "TX",
"city": "Austin",
"country": "USA",
"postalCode": "78701"
}
}
}
Why am I receiving this error? If my theory that it is trying to load each too quickly how could I make it wait until the first one is completed?
EDIT: I added a catch block to the JSONDecoder and I get either success of error randomly for each call. It looks similar to this each time I run the app.
JSON Error
JSON Error
JSON Error
JSON Error
Details(name: "Paramount Theatre", location: Film_Bee.ShowtimesView.Location(address: Film_Bee.ShowtimesView.Address(street: "1245 Station Place", state: "TX", city: "Austin", postalCode: "12345", country: "USA"), geoCode: Film_Bee.ShowtimesView.Geo(latitude: "43.12345", longitude: "-44.12345")))
JSON Error
Each time with a different number of success and errors, always in a different order.
EDIT: I have solved the issue and posted the solution as an answer.
The other solution would be to put a delay between each call. How could I achieve this?
The problem is the API only allows 2 calls per a second and I am attempting to make more than this.
To fix this issue I will have to upgrade my account with tmsapi.