发布到 Firebase 时单元格重复多次

Cell is duplicated multiple times when posting to Firebase

我正在制作一个可以 post 消息的应用程序。我将数据存储在 Firebase 中。当我 post 发送一条新消息时,该特定单元格会重复多次(因此我看到 post 2、3、4 次或更多次)。但它只是 Firebase 中的一个 post。当我刷新屏幕时(例如通过对数据进行排序),它又是一个 post。我做错了什么?

这是我的相关代码:

    override func viewDidLoad() {
    super.viewDidLoad()

    DataService.ds.REF_POSTS.observeEventType(.Value, withBlock:  { snapshot in
        let sortByDate = NSUserDefaults.standardUserDefaults().boolForKey("sortByDate")
        if sortByDate == true {
            self.sortingByDate()
            self.tableView.reloadData()
        } else {
            self.sortingByLikes()
            self.tableView.reloadData()
        }
    })
}

按日期排序数据:

func sortingByDate() {
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "sortByDate")
    sortDateBtn.setTitleColor(UIColor(red: 255/255, green: 102/255, blue: 102/355, alpha: 1.0), forState: .Normal)
    sortLikeBtn.setTitleColor(UIColor(red: 76/255, green: 76/255, blue: 76/355, alpha: 1.0), forState: .Normal)

    if (searchController.active) {
        self.posts = []
        DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.ChildAdded, withBlock: { snapshot in
            if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
                let key = snapshot.key
                let post = Post(postKey: key, dictionary: postDict)
                self.posts.insert(post, atIndex: 0)
            }
            if let searchText = self.searchController.searchBar.text {
                self.filterContent(searchText)
                self.tableView.reloadData()
            }
        })
    } else {
        self.posts = []
        DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.ChildAdded, withBlock: { snapshot in
            if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
                let key = snapshot.key
                let post = Post(postKey: key, dictionary: postDict)
                self.posts.insert(post, atIndex: 0)
            }
            self.tableView.reloadData()
        })
    }
}

按喜欢排序数据:

func sortingByLikes() {
    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "sortByDate")
    sortLikeBtn.setTitleColor(UIColor(red: 255/255, green: 102/255, blue: 102/355, alpha: 1.0), forState: .Normal)
    sortDateBtn.setTitleColor(UIColor(red: 76/255, green: 76/255, blue: 76/355, alpha: 1.0), forState: .Normal)

    if (searchController.active) {
        self.posts = []
        DataService.ds.REF_POSTS.queryOrderedByChild("likes").observeEventType(.ChildAdded, withBlock: { snapshot in
            if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
                let key = snapshot.key
                let post = Post(postKey: key, dictionary: postDict)
                self.posts.insert(post, atIndex: 0)
            }
            if let searchText = self.searchController.searchBar.text {
                self.filterContent(searchText)
                self.tableView.reloadData()
            }
        })
    } else {
        self.posts = []
        DataService.ds.REF_POSTS.queryOrderedByChild("likes").observeEventType(.ChildAdded, withBlock: { snapshot in
            if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
                let key = snapshot.key
                let post = Post(postKey: key, dictionary: postDict)
                self.posts.insert(post, atIndex: 0)
            }
            self.tableView.reloadData()
        })
    }
}

发布到 Firebase:

func postToFirebase(imgUrl: String?) {
    let imageForProfile = NSUserDefaults.standardUserDefaults().valueForKey("profileImage")
    var post: Dictionary<String, AnyObject> = [
        "title": titleTextField.text!,
        "description": descriptionTextField.text!,
        "likes": 0,
        "location": locationTextField.text!,
        "username": usernameDisplay.text!,
        "uid": NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID)!,
        "img": String(imageForProfile!),
        "timestamp": NSDate.timeIntervalSinceReferenceDate(),
        "lat": lat,
        "long": long,
        ]

        if imgUrl != nil {
            post["imageUrl"] = imgUrl
        }

let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
let url = NSURL(fileURLWithPath: "\(firebasePost)")
let lastComponent = url.lastPathComponent

    if lastComponent != nil {
        post["postKey"] = lastComponent!
    }

firebasePost.setValue(post)

titleTextField.text = ""
descriptionTextField.text = ""
locationTextField.text = ""
imageField.image = UIImage(named: "camera")
imageSelected = false

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "sortByDate")
}

表格视图:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
        let postList = searchController.active ? searchResult[indexPath.row] : posts[indexPath.row]
        let post = postList
        cell.request?.cancel()

        var image: UIImage?
        if let url = post.postImgUrl {
            image = FeedVC.imageCache.objectForKey(url) as? UIImage
        }

        var image2: UIImage?
        if let url2 = post.userImgUrl {
            image2 = FeedVC.imageCache.objectForKey(url2) as? UIImage
        }

        cell.configureCell(post, img: image, img2: image2)

        return cell
    } else {
        return PostCell()
    }
}

我的cell.configurecell实现:

    func configureCell(post: Post, img: UIImage?, img2: UIImage?) {
    self.post = post
    likeRef = DataService.ds.REF_USER_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)

    self.descriptionText.text = post.postDescription
    self.descriptionText.scrollRangeToVisible(NSMakeRange(0, 0))
    self.likes = post.likes
    self.likesLbl.text = "\(post.likes) likes"
    self.postTitle.text = post.postTitle
    self.postLocation.text = post.postLocation
    self.username.text = post.username
    self.postKeyLbl.text = post.key
    self.lat = post.lat
    self.long = post.long

    if post.postImgUrl != nil {
        if img != nil {
            self.showcaseImg.image = img
        } else {
            request = Alamofire.request(.GET, post.postImgUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
                if err == nil {
                    let _img = UIImage(data: data!)!
                    self.showcaseImg.image = img
                    FeedVC.imageCache.setObject(_img, forKey: self.post.postImgUrl!)
                } else {
                    print(err.debugDescription)
                }
            })
        }
    } else {
        self.showcaseImg.hidden = true
    }

    if post.userImgUrl != nil {
        if img2 != nil {
            self.profileImg.image = img2
        } else {
            request = Alamofire.request(.GET, post.userImgUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
                if err == nil {
                    let _img2 = UIImage(data: data!)!
                    self.profileImg.image = img2
                    FeedVC.imageCache.setObject(_img2, forKey: self.post.userImgUrl!)
                } else {
                    print(err.debugDescription)
                }
            })
        }
    } else {
        print("no image")
    }

    likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
        if snapshot.value is NSNull {
            self.likesImg.image = UIImage(named: "heart")
        } else {
            self.likesImg.image = UIImage(named: "heart-filled")
        }
    })

    let getUid = NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID)
    if String(getUid!) == (self.post.postUid) {
        editBtn.hidden = false
        delBtn.hidden = false

        let usernameDefaults = NSUserDefaults.standardUserDefaults().valueForKey("username")
        if usernameDefaults != nil {
            username.text = String(usernameDefaults!)
        }

        let checkIfImageChanged = NSUserDefaults.standardUserDefaults().boolForKey("imgIsChanged")
        if checkIfImageChanged == true {
            self.changePost()
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "imgIsChanged")
        }
    } else {
        editBtn.hidden = true
        delBtn.hidden = true
    }

    mapVC.markerTitle = postTitle.text
    mapVC.markerSnippet = postLocation.text
    mapVC.markerLat = lat
    mapVC.markerLong = long
}

感谢您的帮助!

由于您使用的是委托方法tableView.dequeueReusableCellWithIdentifier,当您请求一个新单元格时,如果您不使用新数据更新新单元格,它将带来一个包含旧数据的单元格。为了确定,我需要查看您的 cell.configureCell 实施。