'попытка вставить строку 0 в раздел 0, но в разделе 0 после обновления осталось только 0 строк' - PullRequest
0 голосов
/ 08 декабря 2018

Попытка извлечь хранилище изображений в базе данных firebase и отобразить его в виде таблицы, но при этом появляется ошибка

"необработанное исключение 'NSInternalInconsistencyException', причина: 'попытка вставить строку 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)
            })
        }
    }   
}

}

1 Ответ

0 голосов
/ 08 декабря 2018

Используйте это:

self.tableVC.beginUpdates()
self.tableVC.insertRows(at: [indexpath], with: .top)
self.tableVC.endUpdates()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...