im正在尝试上传图像,所以当一个人上传图像时,它将显示在其供稿中,但是我遇到了致命错误:该行的索引超出范围:cell.imageee.sd_setImage(with:URL(string:self.userImageArray [indexPath.row]))提要单元:有人可以告诉我是什么原因造成的,以及如何解决它,因为这使我发疯。
import UIKit
import Firebase
import SDWebImage
class FeedController: UIViewController ,
UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableV: UITableView!
var userEmailArray = [String] ()
var userCommentArray = [String] ()
var likeArray = [Int] ()
var userImageArray = [String] ()
override func viewDidLoad() {
super.viewDidLoad()
tableV.delegate = self
// tablev.datasource = self
tableV.dataSource = self
getDataFromFirestore()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return userEmailArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier:"cellTable" ,
for: indexPath) as! Feed
cell.user.text = userEmailArray[indexPath.row]
cell.like.text = String(likeArray [indexPath.row])
cell.comment.text = userCommentArray[indexPath.row]
cell.imageee.sd_setImage(with: URL(string:
self.userImageArray[indexPath.row]))
return cell
}
func getDataFromFirestore(){
let fireStoreDatabase = Firestore.firestore()
// let settings = fireStoreDatabase.settings
//settings.areTimestampsInSnapshotsEnabled = true
// fireStoreDatabase.settings = settings
fireStoreDatabase.collection("post").addSnapshotListener { (snapshot, error) in
if error != nil {
print(error?.localizedDescription)
}else{
if snapshot?.isEmpty != true && snapshot != nil {
for document in snapshot!.documents {
let documentID = document.documentID
if let postedby = document.get("postedby") as? String {
self.userEmailArray.append(postedby)
}
if let postComment = document.get("postComment") as? String{
self.userCommentArray.append(postComment)
}
if let likes = document.get("likes") as? Int{
self.likeArray.append(likes)
}
if let imageUrl = document.get("imageurl") as? String {
self.userImageArray.append(imageUrl)
}
self.tableV.reloadData()
}
// snapshot!.documents
}
}
}
}
}
首先,请勿使用4个不同的数组。而是创建一个结构,该结构保留与来自数据库查询的一个响应相对应的属性
struct Post {
let postedBy: String?
let postComment: String?
let likes: Int?
let imageUrl: String?
}
然后将您现在拥有的所有4个数组属性替换为
var posts = [Post]()
并填写到响应结束中
for document in snapshot!.documents {
let postedby = document.get("postedby") as? String
let postComment = document.get("postComment") as? String
let likes = document.get("likes") as? Int
let imageUrl = document.get("imageurl") as? String
posts.append(Post(postedBy: postedBy, postComment: postComment, likes: likes, imageUrl: imageUrl)
}
由于所有属性都是可选的(是否需要?),因此在单元格中设置值时需要检查它们
let post = posts[indexPath.row]
cell.user.text = post.postedBy ?? ""
...
if let imageUrl = post.imageUrl, let url = URL(string: imageUrl) {
cell.imageee.sd_setImage(with: url)
}
您的userImageArray
包含的条目少于userEmailArray
。
您应该有一个包含User
模型实例的数组,该实例捆绑了一个用户的所有数据,包括图像和占位符。