Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cell is duplicated multiple times when posting to Firebase

I'm making an app in which I can post messages. I store my data in Firebase. When I'm posting a new message, that particular cell is duplicating multiple times (so I see the post like 2, 3, 4 or more times). But it's just one post in Firebase. And when I'm refreshing my screen (by for example sorting the data), it's just one post again. What am I doing wrong?

Here's my relevant code:

    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()
        }
    })
}

Sorting data by date:

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()
        })
    }
}

Sorting data by likes:

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()
        })
    }
}

Posting to 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")
}

Tableview:

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()
    }
}

My cell.configurecell implementation:

    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
}

Thanks for your help!

like image 572
debbiedowner Avatar asked Nov 09 '22 14:11

debbiedowner


1 Answers

Since you are using the delegate method tableView.dequeueReusableCellWithIdentifier, when you request a new cell, if you don't update the new cell with new data, it will bring a cell with old data. To be sure I'll need to see your cell.configureCell implementation.

like image 95
felipenbrito Avatar answered Nov 15 '22 06:11

felipenbrito