数据更新后tableview不重新加载数据

时间:2018-08-31 15:55:41

标签: swift uitableview core-data

此视图控制器有两个孩子,同一个类型有两个实例。该孩子有一个表格视图和一个指示是否收藏夹的按钮,当单击该按钮时,按钮的更改为预期的tincolor,但第二个孩子没有像预期的那样重新加载数据。

 Module not found: Error: Can't resolve 'sass-loader' in
          '/data/development ...

现在在父视图控制器中,协议功能实现

protocol favoritesUpdate{
 func uppdateFavorites()
}

class chatListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var type: Bool?
var data:[message]?
var filter: [Chat] = []//[NSManagedObject] = [] 
let rootRef = Database.database().reference()
let chatsRef = Database.database().reference(withPath: "chats")
var chats: [Chat] = []
//let appDelegate =
var isfilter = false
var controllername: String?
var delegate: favoritesUpdate?
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
lazy private var backgroundViewWhenDataIsEmpty: UIView = { return UINib(nibName: "nochat", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView }()

override func viewDidLoad() {
    super.viewDidLoad()
    print("type is \(type) in \(controllername)")
    self.tableView.dataSource = self
    self.tableView.delegate = self
    tableView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "Fondo chat"))
    tableView.backgroundView?.alpha = 0.49
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    print("ya aparecio")
    self.readUserFromCD({ [weak self] _ in
        self?.tableView.reloadData()
        if type!{
            print("observing chats")
            observeChat()
        }
    })
}


 func readUserFromCD(_ completion:(_ data: Bool)->Void){        
            let fetchRequest = NSFetchRequest<Chat>(entityName: "Chat")
            do {
                if type == false{
                    let temp =  try managedContext.fetch(fetchRequest)
                    self.chats = temp.filter({
                        //$0.value(forKey: "favorite") as! Bool == true
                        if let value = $0.value(forKeyPath: "favorite"){
                            if value as! Bool == true {
                                return true
                            }
                        }
                        return false//if  != nil &&
                    })
                    //self.tableView.reloadData()
                }else{
                    self.chats = try managedContext.fetch(fetchRequest)
                    print(self.chats.count)
                }
                print("mostrando los valores de user \(chats)")
                completion(true)
            } catch {
                print("Could not fetch. \(error.localizedDescription)")
                completion(false)
            }
        }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("isFilter \(isfilter)")
        if !isfilter && chats.count > 0{
            tableView.backgroundView?.removeFromSuperview()
            tableView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "Fondo chat"))
            tableView.separatorStyle = .singleLine
            return chats.count
        }else if isfilter && filter.count > 0{
            tableView.backgroundView?.removeFromSuperview()
            tableView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "Fondo chat"))
            tableView.separatorStyle = .singleLine
            return filter.count
        }else{
            tableView.separatorStyle = .none
            showBackgroundIfEmpty()
        }
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! chatsTableViewCell
        var user: NSManagedObject!
        if !isfilter{
            user = chats[indexPath.row]
        }else{
            user = filter[indexPath.row]
        }
        cell.backgroundColor = .clear
        cell.imagen.sd_cancelCurrentImageLoad()
        cell.imagen.layer.borderWidth = 1.0
        cell.imagen.layer.borderColor = lightBlue.cgColor
        cell.imagen.layer.cornerRadius = cell.imagen.frame.width / 2
        cell.imagen.clipsToBounds = true
        cell.imagen.contentMode = .center
        if let url = user.value(forKey: "url") as? String{
            print("there is a image")
            //cell.imagen.sd_setHighlightedImage(with: URL(string: url), options: .progressiveDownload, completed: nil)
            cell.imagen.sd_setImage(with: URL(string: url), placeholderImage: #imageLiteral(resourceName: "ico_perfil"), options: .progressiveDownload, completed: nil)
            cell.imagen.contentMode = .scaleToFill
        }else{
            print("there is not image")
            cell.imagen.contentMode = .center
        }
        if let  name = user.value(forKey: "name") as? String{
            cell.name.text = name
        }
        if let message = user.value(forKey: "message") as? String{
            cell.conversation.text = message
        }
        if let favorite = user.value(forKey: "favorite") as? Bool{
            if favorite{
                cell.favorites.tintColor = lightBlue
            }
        }
        cell.favorites.tag = indexPath.row
        //chats[indexPath.row].value(forKey: "favorite") as? Bool == true ? (cell.favorites.tintColor = lightBlue) : (cell.favorites.tintColor = grey)
        cell.favorites.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        cell.favorites.addTarget(self, action: #selector(self.setFavorite(_:)), for: .touchUpInside)
        return cell
    }
func observeChat(){
    var key: String?
    Constants.refs.databaseChats.observe(.childAdded, with: { [weak self] snapshot in
        print("the key \(snapshot.key) y \(snapshot.key.contains(String(requestManager.instance.user.id!)))")
        if snapshot.key.contains(String(requestManager.instance.user.id!)){
            key = snapshot.key
            if let snap = snapshot.children.allObjects as? [DataSnapshot]{
                if let last = snap.last{
                    if let dat = last.value as? [String: Any]{
                        //let id = dat["id"] as! String
                        var message = dat["body"] as? String
                        let senderId = dat["senderId"] as! String
                        let recipientId = dat["recipientId"] as! String
                        var userid = ""
                        var name: String?
                        var preurl: String?
                        let id = snapshot.key
                        if recipientId != requestManager.instance.user.id!.description && senderId == requestManager.instance.user.id!.description{
                            userid = recipientId
                            if dat["attachmentType"] as? Int == 2 {
                                message = "le envio una imagen"
                            }
                        }else if recipientId == requestManager.instance.user.id!.description && senderId != requestManager.instance.user.id!.description {
                            userid = senderId
                            if dat["attachmentType"] as? Int == 2 {
                                message = "envió una imagen"
                            }
                        }
                        Constants.refs.databaseUser.child(userid).observeSingleEvent(of: .value, with: {snap in
                            print(snap.value as Any)
                                let da = snap.value as! [String: Any]
                            name = da["name"] as? String
                            preurl = da["image"] as? String
                            self?.setChats(id: id, name: name!, message: message!, preurl: preurl!, key: id)
                        })
                    }
                }
            }
        }
    })
}
    func setChats(id: String, name: String, message: String, preurl: String, key: String){
    print("values recibed \(name), \(message),\(preurl),\(key),\(id)")
    print("type is \(type) in \(controllername)")
    if type!{
        print("aqui llego")
        var miChat: Chat?
        //let managedContext = self.appDelegate.persistentContainer.viewContext
        let fetchRequest: NSFetchRequest<Chat> = Chat.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "id = %@", id)//NSPredicate(format: "%K == %@", #keyPath(Chat.id), self.id!)
        do {
            let results = try managedContext.fetch(fetchRequest)
            if results.count > 0 {
                print("chat Found")
                miChat = results.first
                miChat?.message = message
                print("mi chat is \(miChat)")
                try managedContext.save()
                DispatchQueue.main.async {
                    print("the values in \(self.chats.count)")
                    self.tableView.reloadData()
                }

//                  self.tableView.reloadData()
                } else {
                    // Fido not found, create Fido
                    print("not found \(id)")
                    miChat = Chat(context: managedContext)
                    miChat?.id = id
                    miChat?.name = name
                    miChat?.message = message
                    miChat?.url = preurl
                    miChat?.key = key
                    print(miChat)
                    try managedContext.save()
                    DispatchQueue.main.async {
                        print("the values in \(self.chats.count)")
                        self.tableView.reloadData()
                    }
//                  self.tableView.reloadData()
                }
            } catch let error as NSError {
                print("Fetch error: \(error) description: \(error.userInfo)")
            }
        }else{
            print("no type")
        }       
    }
@objc func setFavorite(_ sender: UIButton){
    let value  = self.chats[sender.tag].value(forKey: "favorite") as? Bool
    value == true ? (sender.tintColor = lightBlue) : (sender.tintColor = grey)
    self.chats[sender.tag].setValue(!value!, forKey: "favorite")
    //let managedContext = self.appDelegate.persistentContainer.viewContext
    do{
        try managedContext.save()
        self.delegate?.uppdateFavorites()
    }catch{
        print(error.localizedDescription)
    }
}

但是更新没有发生。实现这一目标的最佳方法是什么。 编辑:问题然后成为零的代表

0 个答案:

没有答案