【问题标题】:JSON Decoder error when decoding in CollectionView在 CollectionView 中解码时出现 JSON 解码器错误
【发布时间】:2018-12-07 02:46:48
【问题描述】:

我正在获取一组 url 并在 Collection View 中对其进行解码。我之前已成功完成此操作,但这次收到错误消息。

我收到错误消息:

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "给定的数据不是有效的 JSON。",underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON 文本没有开始带有数组或对象以及允许未设置片段的选项。" UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并且允许未设置片段的选项。})))

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

这是我的代码:

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

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

编辑:我在 JSONDecoder 中添加了一个 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

每次都有不同数量的成功和错误,总是以不同的顺序。

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

另一种解决方案是在每次通话之间延迟。我怎样才能做到这一点?

【问题讨论】:

  • 放弃尝试!强制展开并添加一个带有print(error.localizedDescription) 的catch 块。在 JSONDecoder 行放置一个断点,当你点击它时输入po JSONDecoder().decode([Details].self, from: data)。调试器会准确地告诉您问题所在。
  • 您的网址中似乎缺少 zip=。 http://data.tmsapi.com/v1.1/theatres?zip=\(id)&api_key=<your api key>。这是 API 的文档页面:developer.tmsapi.com/io-docs.
  • 复制到浏览器时打印的 url 可以正常工作。就像我说的那样,它会随机完成一两个解码并将详细信息打印到控制台,但在尝试完成下一个时会出错。

标签: ios json swift collectionview jsondecoder


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多