如何解决致命错误:Swift IOS中的索引超出范围

时间:2018-05-21 13:15:11

标签: ios swift rss rss-reader

我有一个代码问题是IOS的RSS阅读器应用程序。我有一个错误线程1:致命错误:索引超出范围。

我写错了哪一行。 顺便说一句,这个错误确实发生在所有的RSS链接我举例如天空新闻RSS URL它运作良好,但有一些网站(如我现在放的那个)它没有运行和写致命错误:索引超出范围ERROR。

守则:

import UIKit

class FeedListViewController: UITableViewController, XMLParserDelegate {

    var myFeed : NSArray = []
    var feedImgs: [AnyObject] = []
    var url: URL!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 140
        tableView.backgroundColor = UIColorFromRGB(rgbValue: 0x00B6ED)
        self.tableView.dataSource = self
        self.tableView.delegate = self

        loadData()
    }

    @IBAction func refreshFeed(_ sender: Any) {

        loadData()
    }

    func loadData() {
        url = URL(string: "https://www.widgeti.co.il/feed")!
        loadRss(url);
    }

    func loadRss(_ data: URL) {
        // XmlParserManager instance/object/variable
        let myParser : XmlParserManager = XmlParserManager().initWithURL(data) as! XmlParserManager
        // Put feed in array
        feedImgs = myParser.img as [AnyObject]
        myFeed = myParser.feeds
        tableView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "openPage" {
            let indexPath: IndexPath = self.tableView.indexPathForSelectedRow!
            let selectedFURL: String = (myFeed[indexPath.row] as AnyObject).object(forKey: "link") as! String
            // Instance of our feedpageviewcontrolelr
            let fivc: FeedItemViewController = segue.destination as! FeedItemViewController
            fivc.selectedFeedURL = selectedFURL as String
        }
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myFeed.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.backgroundColor = UIColor.clear
        cell.detailTextLabel?.backgroundColor = UIColor.clear

        if indexPath.row % 2 == 0 {
            cell.backgroundColor = UIColor(white: 1, alpha: 0.1)
        } else {
            cell.backgroundColor = UIColor(white: 1, alpha: 0.2)
        }

        // Load feed iamge.



        let url = NSURL(string:feedImgs[indexPath.row] as! String) //ERROR Thread 1: Fatal error: Index out of range
        let data = NSData(contentsOf:url! as URL)
        var image = UIImage(data:data! as Data)
        image = resizeImage(image: image!, toTheSize: CGSize(width: 80, height: 80))
        let cellImageLayer: CALayer?  = cell.imageView?.layer
        cellImageLayer!.cornerRadius = 35
        cellImageLayer!.masksToBounds = true
        cell.imageView?.image = image
        cell.textLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "title") as? String
        cell.textLabel?.textColor = UIColor.white
        cell.textLabel?.numberOfLines = 0
        cell.textLabel?.lineBreakMode = .byWordWrapping

        cell.detailTextLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "pubDate") as? String
        cell.detailTextLabel?.textColor = UIColor.white

        return cell
    }

    func UIColorFromRGB(rgbValue: UInt) -> UIColor {
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }

    func resizeImage(image:UIImage, toTheSize size:CGSize)->UIImage{


        let scale = CGFloat(max(size.width/image.size.width,
                                size.height/image.size.height))
        let width:CGFloat  = image.size.width * scale
        let height:CGFloat = image.size.height * scale;

        let rr:CGRect = CGRect(x: 0, y: 0, width: width, height: height)

        UIGraphicsBeginImageContextWithOptions(size, false, 0);
        image.draw(in: rr)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return newImage!
    }
}
你可以帮我解决这个问题吗? 谢谢!

1 个答案:

答案 0 :(得分:2)

  

致命错误:索引超出范围

     

此错误仅指的是您希望从数组访问的索引不存在。

let url = NSURL(string: feedImgs[indexPath.row] as! String)

在上面的行feedImgs[indexPath.row]不存在,这就是你收到错误的原因。确保您的feedImgs数组和myFeed数组的长度相同,因为您要从myFeed数组加载表。

或者,您可以这样检查。

if feedImgs.count > indexPath.row {
    let url = NSURL(string: (feedImgs[indexPath.row] ?? ""))
}