JSON 在 CollectionView 中解码时解码器错误

JSON Decoder error when decoding in CollectionView

我正在获取一组 url 并在集合视图中对它们进行解码。我之前已经成功完成此操作,但这次收到错误消息。

我收到错误消息:

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.})))

我注意到,如果可能的话,它似乎试图在完成另一个之前解码一个。我相信这是因为有时我 运行 应用程序会在抛出错误之前打印一两个解码数据实例。

这是我的代码:

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 }

数组如下所示:

["12345", "23456", "34567", "45678"]

数组正在正确打印到控制台,正在解码的 url 也是如此。它们的显示方式与成功运行的控制器相同。

JSON 看起来像这样:

{
"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"
    }
}
}

为什么我收到这个错误?如果我的理论是它试图加载每个太快,我怎么能让它等到第一个完成?

编辑:我在 JSON 解码器中添加了一个 catch 块,每次调用都会随机获得成功或错误。每次我 运行 应用程序时,它看起来都与此相似。

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

每次成功和错误的次数不同,顺序也不同。

编辑:我已经解决了这个问题并将解决方案作为答案发布。

另一个解决方案是在每次调用之间设置延迟。我怎样才能做到这一点?

问题是 API 每秒只允许 2 次调用,而我正在尝试进行更多调用。

要解决此问题,我必须使用 tmsapi 升级我的帐户。