swift 4 xcode 应用未读取 json 文件

swift 4 xcode app not reading in json file

所以我有一个包含 3 个页面的分页应用程序,每个页面都有一个详细信息视图。所有三个页面(视图)都访问单独的 json 数据文件。一切正常,直到我设置第三个页面视图及其详细视图。现在应用程序似乎无法访问第二个视图的 json 文件。它获取文件的路径并为该文件生成一个本地 URL,但要么没有找到该文件,要么没有从中获取数据。下面是代码:

func downloadJSON(completed: @escaping () -> ()) {
    let path = Bundle.main.path(forResource: "Speedways", ofType: "json")
    let url = URL(fileURLWithPath: path!)

    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil, response != nil else {
            return
        }
        do {
            let decoder = JSONDecoder()
            allspeedways = try decoder.decode([Speedways].self, from: data)
            var s = 0
            for speedway in allspeedways {
                self.TableData.append(speedway[s].speedway.capitalized)
                s += 1
            }
        } catch {
            print(error)
        }
    }.resume()
    DispatchQueue.main.async {
        completed()
    }
}

这是数据模型:

typealias Speedways = [Speedway]

struct Speedway: Codable {
    let speedway, location, sizeOfTrack: String
    let trackEvents, trackevents: [Trackevent]?

    enum CodingKeys: String, CodingKey {
        case speedway = "Speedway"
        case location = "Location"
        case sizeOfTrack = "SizeOfTrack"
        case trackEvents = "TrackEvents"
        case trackevents
    }
}

struct Trackevent: Codable {
    let trackevent, date, pole, winner: String
    let playoff: String
}

这是 json 数据(我不知道为什么这显示很奇怪):

[{"Speedway":"Daytona International Speedway",
"Location":"Daytona, Fla",
"SizeOfTrack":"2.5 miles",
"TrackEvents" :[{
        "trackevent" : "Advance Auto Parts CLASH AT DAYTONA",
        "date" : "Sun, Feb 11",
        "pole" : "Austin Dillon",
        "winner" : "Brad Keselowski",
        "playoff" : "No"
        },
        .
        .
        .
        {
          .
          .
          .
        }]
 },
 {
 "Speedway":"Atlanta Motor Speedway",
 "Location":"Hampton, Ga",
 "SizeOfTrack":"1.54 miles",
 "trackevents" :[{
        "trackevent" : "Folds of Honor QuikTrip 500",
        "date" : "Sun, Feb 25",
        "pole" : "Kyle Busch",
        "winner" : "Kevin Harvick",
        "playoff" : "No"
        }]
 },

错误在执行期间显示在此处,消息为:"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

    speedwaysTableView.delegate = self
    speedwaysTableView.dataSource = self

有人有什么想法吗?

为什么要用 URLSession 在捆绑包中加载数据?可以在没有互联网连接的情况下读取本地文件

删除typealias并获取数据

func downloadJSON() { // the name of the function is pretty misleading
    let url = Bundle.main.url(forResource: "Speedways", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    allspeedways = try! JSONDecoder().decode([Speedway].self, from: data)
    TableData = allspeedways.map{ [=10=].speedway.capitalized }
    // here reload the table view
}

如果代码崩溃,说明您犯了设计错误。

如果 speedwaysTableView.delegate = self 崩溃,接口生成器中未连接插座