发布到Firebase时,单元格会被复制多次 [英] Cell is duplicated multiple times when posting to Firebase

查看:103
本文介绍了发布到Firebase时,单元格会被复制多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个可以发布消息的应用程序。我将数据存储在Firebase中。当我发布一条新消息时,这个特定的单元格会复制多次(所以我会看到这个帖子像2,3,4或更多次)。但这只是Firebase中的一个帖子。而当我刷新我的屏幕(例如通过排序数据),这只是一个职位。

以下是我的相关代码:

 重写func viewDidLoad(){
super.viewDidLoad()

DataService.ds.REF_POSTS.observeEventType(.Value,withBlock:{snapshot in
let sortByDate = NSUserDefaults.standardUserDefaults( ).boolForKey(sortByDate)
如果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)。正常)
sortLikeBtn.setTitleColor(UIColor(红色:76/255,绿色:76/255,蓝色:76/355,alph如果(searchController.active){
self.posts = []
DataService.ds.REF_POSTS.queryOrderedByChild(timestamp ).observeEventType(.ChildAdded,withBlock:{在
中的快照,如果让postDict = snapshot.value为? Dictionary< String,AnyObject> {
let key = snapshot.key
let post = Post(postKey:key,dictionary:postDict)
self.posts.insert(post,atIndex:0)
}
如果让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 $ b $ if 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(红色:255/255,绿色:102/255,蓝色: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)
}
如果让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 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,
]

如果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)

$ / code>

Tableview:

  func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell {
如果let cell = tableView.dequeueReusableCellWithIdentifier(PostCell)为? PostCell {
让postList = searchController.active? searchResult [indexPath.row]:posts [indexPath.row]
let post = postList $ b $ cell.request?.cancel()

var image:UIImage?
如果让url = post.postImgUrl {
image = FeedVC.imageCache.objectForKey(url)as? UIImage
}

var image2:UIImage?
如果让url2 = post.userImgUrl {
image2 = FeedVC.imageCache.objectForKey(url2)as? UIImage


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

return cell
} else {
return PostCell()
}
}

我的cell.configurecell实现: p>

  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

如果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 {$ b $ print(err.debugDescription)

})
}
} else {
self.showcaseImg.hidden = true
}

如果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.value是NSNull {
self.likesImg.image = UIImage(named:heart)
} else {
self.likesImg.image = UIImage(命名为heart-filled)
}
})

let getUid = NSUserDefaults.standardUserDefaults()。valueForKey(KEY_UID)
if String getUid!)==(self.post.postUid){
editBtn.hidden = false
delBtn.hidden = false
$ b $ 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 的实现。


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!

解决方案

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.

这篇关于发布到Firebase时,单元格会被复制多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆