简体   繁体   English

线程 1:致命错误:索引超出范围

[英]Thread 1: Fatal error : Index out of Range

I am trying to read data from the json file data.json but whenever i try to parse and display the data I am getting the error mentioned in the title.我正在尝试从 json 文件 data.json 读取数据,但是每当我尝试解析和显示数据时,我都会收到标题中提到的错误。

I am trying to parse json using codable protocol and can't seem to find the solution of the given error.我正在尝试使用可编码协议解析 json,但似乎无法找到给定错误的解决方案。

HomeTabViewController.swift HomeTabViewController.swift

import UIKit
import FirebaseAuth

class HomeTabViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    //MARK: - Global Variables
    
    var articles = [Article]()
    
    // MARK: - Outlets
    
    @IBOutlet weak var newsTableViewOutlet: UITableView!
    
    // MARK: - Default Functions

    override func viewDidLoad() {
        super.viewDidLoad()
        self.newsTableViewOutlet.dataSource = self
        self.newsTableViewOutlet.delegate = self

        if let localData = self.readLocalFile(forName: "data") {
            self.parse(json: localData)
        }
    }
    
    // MARK: - TableView Functions
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articles.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = newsTableViewOutlet.dequeueReusableCell(withIdentifier: "newsCell", for: indexPath)
        let article = self.articles[indexPath.row]
        cell.textLabel?.text = article.title
        print(article.title)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let rotationTransform = CATransform3DTranslate(CATransform3DIdentity, 0, 30, 0)
        cell.layer.transform = rotationTransform
        cell.alpha = 0.5
        
        UIView.animate(withDuration: 0.75) {
            cell.layer.transform = CATransform3DIdentity
            cell.alpha = 1.0
        }
    }
    
    
    // MARK: - Data Download Functions
    
    // Function to parse JSON
    func parse(json: Data){
        let decoder = JSONDecoder()
        
        if let newsArticles = try? decoder.decode(Articles.self, from: json){
            self.articles = newsArticles.articles
            newsTableViewOutlet.reloadData()
        }
    }
    
    func readLocalFile(forName name: String) -> Data? {
        do {
            if let bundlePath = Bundle.main.path(forResource: name,
                                                 ofType: "json"),
                let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
                return jsonData
            }
        } catch {
            print(error)
        }
        
        return nil
    }
    
    // MARK: Segue Functions
    
    @IBAction func unwindToRootViewController(segue: UIStoryboardSegue) {
        print("Unwind to Root View Controller")
    }
    
    @IBAction func logOutPressed(_ sender: UIButton) {
        print("Log out Button Pressed")
        
        let firebaseAuth = Auth.auth()
        do {
          try firebaseAuth.signOut()
        } catch let signOutError as NSError {
          print ("Error signing out: %@", signOutError)
        }
      
    }

Article.swift文章.swift

struct Article: Codable{
    
    public var title: String
    public var description: String
}

Articles.swift文章.swift

struct Articles: Codable {
    public var articles: [Article]
}

data.json数据.json

{
"status": "ok",
"totalResults": 38,
"articles": [
{},
{
"source": {},
"author": null,
"title": "Blair approves request to boost RCMP presence as Nova Scotia lobster fishery dispute escalates - CBC.ca",
"description": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitter conflict over a First Nations lobster harvest in that pro…",
"url": "https://www.cbc.ca/news/politics/nova-scotia-fishery-conflict-rcmp-1.5766838",
"urlToImage": "https://i.cbc.ca/1.5554196.1588555323!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/ns-shootings-20200420.jpg",
"publishedAt": "2020-10-17T21:16:00Z",
"content": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitt… [+4949 chars]"
},
{
"source": {
"id": null,
"name": "Maple Leafs Hot Stove"
},
"author": "Kevin Papetti",
"title": "Toronto Maple Leafs Offseason: Joe Thornton signing, the odd man out, and the next steps - Maple Leafs Hot Stove",
"description": "What an active week -- and offseason overall -- it's been for Kyle Dubas and the Toronto Maple Leafs. In: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey Anderson (RW), Travis Boyd (C/LW), Aaron Dell (G), Fi…",
"url": "https://mapleleafshotstove.com/2020/10/17/toronto-maple-leafs-offseason-joe-thornton-signing-the-odd-man-out-and-the-next-steps/",
"urlToImage": "https://46wvda23y0nl13db2j3bl1yx-wpengine.netdna-ssl.com/wp-content/uploads/2020/10/jumbo-joe-scaled.jpeg",
"publishedAt": "2020-10-17T20:39:00Z",
"content": "What an active week and offseason overall its been for Kyle Dubas and the Toronto Maple Leafs.\r\nIn: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey… [+10814 chars]"
},
{
"source": {
"id": null,
"name": "AppleInsider"
},
"author": "Malcolm Owen",
"title": "Early MagSafe Charger, iPhone 12 accessory orders start arriving - AppleInsider",
"description": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arriving ahead of the iPhone 12 range.",
"url": "https://appleinsider.com/articles/20/10/17/magsafe-chargers-iphone-12-accessory-orders-start-arriving-with-customers",
"urlToImage": "https://photos5.appleinsider.com/gallery/38304-72729-magsafe-charger-xl.jpg",
"publishedAt": "2020-10-17T19:46:39Z",
"content": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arr… [+1533 chars]"
},
{
"source": {
"id": null,
"name": "Global News"
},
"author": "Simon Little",
"title": "Anti-mask protesters cause disturbance on B.C. ferry, cause unloading delay - Global News",
"description": "A group of about 12 unmasked protesters became belligerent and harassed masked passengers on a morning sailing, according to BC Ferries.",
"url": "https://globalnews.ca/news/7403621/anti-mask-protesters-cause-disturbance-delay-b-c-ferry/",
"urlToImage": "https://globalnews.ca/wp-content/uploads/2018/02/01172660.jpg?quality=85&strip=all&crop=0px%2C111px%2C3000px%2C1579px&resize=720%2C379",
"publishedAt": "2020-10-17T19:30:51Z",
"content": "A group of anti-mask protesters has been banned from BC Ferries for the rest of the day after causing a disturbance on a morning sailing from Nanaimo to Horseshoe Bay.\r\nThe incident happened on the 8… [+2038 chars]"
},
{
"source": {
"id": "cbc-news",
"name": "CBC News"
},
"author": null,
"title": "Chechen teen killed by police named as suspect in teacher's beheading in France - CBC.ca",
"description": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on social media minutes after the attack, officials said Saturday.",
"url": "https://www.cbc.ca/news/world/france-teacher-beheading-chechen-1.5766742",
"urlToImage": "https://i.cbc.ca/1.5766755.1602956271!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/aptopix-france-teacher-decapitated.jpg",
"publishedAt": "2020-10-17T18:43:00Z",
"content": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on so… [+5743 chars]"
}
}

It seems the JSON is not valid. JSON 似乎无效。 I ran it through jsonlint.com我通过 jsonlint.com 运行它

I also removed the empty article at the top.我还删除了顶部的空文章。 This might cause an issue when instantiating an Article from the JSON data.从 JSON 数据实例化Article时,这可能会导致问题。

Here's the fixed version:这是固定版本:

{
    "status": "ok",
    "totalResults": 38,
    "articles": [
        {
            "source": {},
            "author": null,
            "title": "Blair approves request to boost RCMP presence as Nova Scotia lobster fishery dispute escalates - CBC.ca",
            "description": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitter conflict over a First Nations lobster harvest in that pro…",
            "url": "https://www.cbc.ca/news/politics/nova-scotia-fishery-conflict-rcmp-1.5766838",
            "urlToImage": "https://i.cbc.ca/1.5554196.1588555323!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/ns-shootings-20200420.jpg",
            "publishedAt": "2020-10-17T21:16:00Z",
            "content": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitt… [+4949 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Maple Leafs Hot Stove"
            },
            "author": "Kevin Papetti",
            "title": "Toronto Maple Leafs Offseason: Joe Thornton signing, the odd man out, and the next steps - Maple Leafs Hot Stove",
            "description": "What an active week -- and offseason overall -- it's been for Kyle Dubas and the Toronto Maple Leafs. In: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey Anderson (RW), Travis Boyd (C/LW), Aaron Dell (G), Fi…",
            "url": "https://mapleleafshotstove.com/2020/10/17/toronto-maple-leafs-offseason-joe-thornton-signing-the-odd-man-out-and-the-next-steps/",
            "urlToImage": "https://46wvda23y0nl13db2j3bl1yx-wpengine.netdna-ssl.com/wp-content/uploads/2020/10/jumbo-joe-scaled.jpeg",
            "publishedAt": "2020-10-17T20:39:00Z",
            "content": "What an active week and offseason overall its been for Kyle Dubas and the Toronto Maple Leafs.\r\nIn: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey… [+10814 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "AppleInsider"
            },
            "author": "Malcolm Owen",
            "title": "Early MagSafe Charger, iPhone 12 accessory orders start arriving - AppleInsider",
            "description": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arriving ahead of the iPhone 12 range.",
            "url": "https://appleinsider.com/articles/20/10/17/magsafe-chargers-iphone-12-accessory-orders-start-arriving-with-customers",
            "urlToImage": "https://photos5.appleinsider.com/gallery/38304-72729-magsafe-charger-xl.jpg",
            "publishedAt": "2020-10-17T19:46:39Z",
            "content": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arr… [+1533 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Global News"
            },
            "author": "Simon Little",
            "title": "Anti-mask protesters cause disturbance on B.C. ferry, cause unloading delay - Global News",
            "description": "A group of about 12 unmasked protesters became belligerent and harassed masked passengers on a morning sailing, according to BC Ferries.",
            "url": "https://globalnews.ca/news/7403621/anti-mask-protesters-cause-disturbance-delay-b-c-ferry/",
            "urlToImage": "https://globalnews.ca/wp-content/uploads/2018/02/01172660.jpg?quality=85&strip=all&crop=0px%2C111px%2C3000px%2C1579px&resize=720%2C379",
            "publishedAt": "2020-10-17T19:30:51Z",
            "content": "A group of anti-mask protesters has been banned from BC Ferries for the rest of the day after causing a disturbance on a morning sailing from Nanaimo to Horseshoe Bay.\r\nThe incident happened on the 8… [+2038 chars]"
        },
        {
            "source": {
                "id": "cbc-news",
                "name": "CBC News"
            },
            "author": null,
            "title": "Chechen teen killed by police named as suspect in teacher's beheading in France - CBC.ca",
            "description": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on social media minutes after the attack, officials said Saturday.",
            "url": "https://www.cbc.ca/news/world/france-teacher-beheading-chechen-1.5766742",
            "urlToImage": "https://i.cbc.ca/1.5766755.1602956271!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/aptopix-france-teacher-decapitated.jpg",
            "publishedAt": "2020-10-17T18:43:00Z",
            "content": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on so… [+5743 chars]"
        }
    ]
}

EDIT: I've added a working gist编辑:我添加了一个工作要点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM