从集合视图中的数组中获取字符串时超出索引范围

时间:2018-12-15 14:01:24

标签: arrays swift

我希望我的应用程序在collectionview中显示mysql数据库中的数据,因此我在viewDidload()中写下mysql连接代码,并使其以数组格式显示,除了在collectionview中显示数据外,其他一切都很好,这是我的代码

var subjectlist = ""
var imgurllist = ""
var subjectarray = [String]()
var imgurllistarray = [String]()
    override func viewDidLoad() {
    super.viewDidLoad()
    collectionview.dataSource = self
    collectionview.delegate = self
    let request = NSMutableURLRequest(url: NSURL(string: [Point to file on my server])! as URL)
    let urlsession =  URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        DispatchQueue.main.async {
            do {
                if let dataunwarp = data {
                    let json =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                    if let parseJSON = json {
                        if let subjectnotfound = parseJSON["subjectnotfound"]{
                            let alert = UIAlertController(title: "เกิดข้อผิดพลาด", message: "ไม่พบ subject ในเซิฟเวอร์ กรุณาลองใหม่อีกครั้ง", preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "ปิด", style: .default, handler: { (alert: UIAlertAction!) in
                                self.navigationController?.popViewController(animated: true)
                            }))
                            self.dismiss(animated: false, completion: { () in self.present(alert, animated: true, completion: nil) })
                        } else {
                            self.subjectlist = parseJSON["subjectlist"] as! String
                            self.imgurllist = parseJSON["imgurllist"] as! String
                            self.subjectarray = Array(self.subjectlist.components(separatedBy: ","))
                            print("subjectarray=\(self.subjectarray)")
                            print(self.subjectarray[0])
                            //self.imgurllistarray = Array(self.imgurllist.components(separatedBy: ","))

                        }
                    } else {
                        let alert = UIAlertController(title: "เกิดข้อผิดพลาด", message: "เกิดข้อผิดพลาดจากเซิฟเวอร์", preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "ปิด", style: .default, handler: { (alert: UIAlertAction!) in
                            self.navigationController?.popViewController(animated: true)
                        }))
                        self.dismiss(animated: false, completion: { () in self.present(alert, animated: true, completion: nil) })
                    }
                } else {
                    let alert = UIAlertController(title: "เกิดข้อผิดพลาด", message: "เกิดข้อผิดพลาดจากเซิฟเวอร์", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "ปิด", style: .default, handler: { (alert: UIAlertAction!) in
                        self.navigationController?.popViewController(animated: true)
                    }))
                    self.dismiss(animated: false, completion: { () in self.present(alert, animated: true, completion: nil) })
                }
            } catch {
                let alert = UIAlertController(title: "เกิดข้อผิดพลาด", message: "ไม่สามารถติดต่อกับเซิฟเวอร์ได้ กรุณาตรวจสอบการเชื่อมต่ออินเตอร์เน็ตเเละลองใหม่อีกครั้ง", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "ปิด", style: .default, handler: { (alert: UIAlertAction!) in
                    self.navigationController?.popViewController(animated: true)
                }))
                self.dismiss(animated: false, completion: { () in self.present(alert, animated: true, completion: nil) })
            }
        }})
    urlsession.resume()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return subject.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! collectionviewcell
    let subjectimgurl = NSMutableURLRequest(url: NSURL(string: "https://psmapps.com/psmatstamp/images/atstamp.png")! as URL)

     let imgsession =  URLSession.shared.dataTask(with: subjectimgurl as URLRequest, completionHandler: {data, response, error -> Void in
        if let e = error {
            print("Error downloading picture: \(e)")
        } else {
            // No errors found.
            // It would be weird if we didn't have a response, so check for that too.
            if let res = response as? HTTPURLResponse {
                if let imageData = data {
                    // Finally convert that Data into an image and do what you wish with it.
                    let subjectimg = UIImage(data: imageData)
                    DispatchQueue.main.async {
                        cell.subjectimage.image = subjectimg
                    }
                } else {
                    print("Couldn't get image: Image is nil")
                }
            } else {
                print("Couldn't get response code for some reason")
            }
        }
     })
    imgsession.resume()


    cell.subjectlabel.text = subjectarray[indexPath.item]
    print(self.subjectarray[indexPath.item])
    cell.layer.borderColor = UIColor.lightGray.cgColor
    cell.layer.borderWidth = 0.5
    return cell
}

在显示此视图之前,此行发生了错误

cell.subjectlabel.text = subjectarray[indexPath.item]

错误消息:“索引超出范围”,但是当我取消注释发生错误的行并从subjectarray打印出数据时,我可以看到数组类型的数据 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

numberOfItemsInSection

return subject.count

然后在cellForItemAt中使用

subjectarray[indexPath.item]

是否可以保证两者一次都相同大小,还可以使用SDWebImage加载图像

还需要重新加载数据

self.subjectarray = Array(self.subjectlist.components(separatedBy: ","))                  
self.collectionView.reloadData()

UIAlertController到处都是紧凑代码的好方法,请考虑制作扩展名/函数并用适当的消息调用它