致命错误:索引超出范围(尝试将图像加载到表格视图时)

时间:2017-07-03 11:48:22

标签: json swift

我正在尝试从网址加载图片,这是代码:

import UIKit

class TripsTableViewCell : UITableViewCell
{

    @IBOutlet weak var tripName: UILabel!
    @IBOutlet weak var tripImage: UIImageView!
}
    //let urlString = "http://127.0.0.1:8000/v1/trips/"

class TripsTableViewController: UITableViewController {
var myIndex = 0
var trips = [Trip]()
var tripNameArray = [String]()
var tripImageArray = [String]()



override func viewDidLoad() {
    super.viewDidLoad()
    self.newGetFunction()

    /*let trip0:Trip = Trip(id: 1, name: "Dead Sea", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")
    let trip1:Trip = Trip(id: 1, name: "Aaqaba", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")


    let trip2:Trip = Trip(id: 1, name: "Maeen", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")


    let trip3:Trip = Trip(id: 1, name: "Petra", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")


    let trip4:Trip = Trip(id: 1, name: "Jerash", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")

    let trip5:Trip = Trip(id: 1, name: "Um Qais", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")


    let trip6:Trip = Trip(id: 1, name: "Amman", location: "Amman", hostedBy: "Tarek", time: "8:00", spokenLanguage: "English", maxPeople: 25, meetingPoint: "7th Circle", image: "https://ichef-1.bbci.co.uk/news/976/cpsprodpb/75E7/production/_89938103_deadseadrone.jpg")

    trips.append(trip0)
    trips.append(trip1)
    trips.append(trip2)
    trips.append(trip3)
    trips.append(trip4)
    trips.append(trip5)
    trips.append(trip6)

    print("HERE")
    print(trips)
    */
    tableView.delegate = self;
    tableView.dataSource = self;
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source


override func numberOfSections(in tableView: UITableView)-> Int{
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return tripNameArray.count
}


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TripsTableViewCell
    cell.tripName.text = tripNameArray[indexPath.row]
    //cell.tripImage.downloadImage(from: self.tripImageArray[indexPath.row])
   let imgURL = NSURL(string: tripImageArray[indexPath.row])
    if imgURL != nil{
        let data = NSData(contentsOf: (imgURL as URL?)!)
        cell.tripImage.image = UIImage(data: data! as Data)
    }

    //Nart's Work

    /*cell.tripImage.image = UIImage(named: trips[indexPath.row].Image)
    let t = trips[indexPath.row]
    cell.tripName.text = t.Name
    print(indexPath.row)
    print(trips[indexPath.row].Name)*/

    return cell
}


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    myIndex = indexPath.row
    NSLog("%d",myIndex)
    performSegue(withIdentifier: "segue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}

func newGetFunction()
{
    let url = URL (string: "http://127.0.0.1:8000/v1/trips/")
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(myJson)
                    var myJsonArray = (myJson as! NSArray) as Array
                    for trip in myJsonArray
                    {
                        if let tripDict = trip as? NSDictionary{
                            if let name = tripDict.value(forKey: "name"){
                                self.tripNameArray.append(name as! String)
                            }
                            if let name = tripDict.value(forKey: "image"){
                                if let imgName = (name as? String){
                                self.tripImageArray.append((imgName as? String)!)
                            }
                            }
                            OperationQueue.main.addOperation ({
                                self.tableView.reloadData()
                            })
                        }
                    }
                }
                catch
                {
                }
            }
        }
    }
    task.resume()
}

}

我在这一行收到错误: -

   let imgURL = NSURL(string: tripImageArray[indexPath.row])

,错误是: -

1)PAC Fetch失败,错误为[NSURLErrorDomain:-1003]

2)[] nw_proxy_resolver_create_parsed_array PAC评估错误:NSURLErrorDomain:-1003

3)致命错误:指数超出范围

2 个答案:

答案 0 :(得分:0)

您尝试将tripImageArray中的每个项目显示在表格视图中,但对于numberOfRowsInSection功能,您将返回tripNameArray的计数。显然,您的tripNameArray数组的元素多于tripImageArray,因此您收到此错误。

您需要从其中一个中选择作为桌面视图的计数。

答案 1 :(得分:0)

tripImageArray和tripNameArray的大小不相似,将newGetFunction的部分更改为:

test