试图获取firebase中存储的图像并将其显示在表视图中,但显示错误
"未捕获的异常'NSInternalConsistencyException',原因:'试图将行0插入节0,但中只有0行更新后的第0节">
class galleryVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableVC: UITableView!
var images = [imageUpload]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem?.title = "Camera"
Database.database().reference().child("CameraPhoto").observe(.childAdded){ (snapshot) in
DispatchQueue.main.async {
let newImage = imageUpload(snapshot: snapshot)
self.images.insert(newImage, at: 0)
let indexpath = IndexPath(row: 0, section: 0)
self.tableVC.insertRows(at: [indexpath], with: .top)
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableVC.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellVC
cell.post = self.images[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
用于上传图像的ImageUpload方法的代码:-
class imageUpload
{
var imageDownloadUrl:String?
private var image :UIImage!
var label1:String!
var label2:String!
var label3:String!
var label4:String!
init(image:UIImage,label1:String,label2:String,label3:String,label4:String) {
self.image = image
self.label1 = label1
self.label2 = label2
self.label3 = label3
self.label4 = label4
}
init(snapshot: DataSnapshot) {
let json = JSON(snapshot.value)
self.imageDownloadUrl = json["imgDownloadURL"].stringValue
self.label1 = json["label1"].stringValue
self.label2 = json["label2"].stringValue
self.label3 = json["label3"].stringValue
self.label4 = json["label4"].stringValue
}
func upload()
{
//1.new Database Refrence
let newImg = Database.database().reference().child("CameraPhoto").childByAutoId()
let newImgKey = newImg.key
//convert image into data
if let imgData = self.image.jpegData(compressionQuality: 0.6){
//2.new Storage Refrence
let ImgStorageRef = Storage.storage().reference().child("images")
let newImgRef = ImgStorageRef.child(newImgKey!)
//save the image into storage
newImgRef.putData(imgData).observe(.success) { (snapshot) in
//save the label and downloadURL()
snapshot.reference.downloadURL(completion: { (url, error) in
self.imageDownloadUrl = url?.absoluteString
let newImgDictionary = [
"imgDownloadURL" :self.imageDownloadUrl,
"label1":self.label1,
"label2":self.label2,
"label3":self.label3,
"label4":self.label4
]
newImg.setValue(newImgDictionary)
})
}
}
}
}
使用此:
self.tableVC.beginUpdates()
self.tableVC.insertRows(at: [indexpath], with: .top)
self.tableVC.endUpdates()