Joh*_*ieh 2 tableview firebase swift firebase-realtime-database firebase-storage
我使用新的Firebase制作了一个简单的社交媒体,并且我成功地将带有数据库和图像的字符串与存储一起保存,但是当它将数据检索回到表格时,不寻常的事情发生了!
所有图像检索回来随机显示并不断移位,但其他部分显示完美或当我使用返回posts.count tableView显示没有帖子.
希望有人能给我一些建议
import UIKit
import Firebase
import FirebaseStorage
class timelineTableViewController: UITableViewController {
var posts = [Post]()
var databaseRef: FIRDatabaseReference!
var storageRef: FIRStorageReference!
override func viewDidLoad() {
super.viewDidLoad()
databaseRef = FIRDatabase.database().reference()
storageRef = FIRStorage.storage().reference()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return posts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "postCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)as! timelineTableViewCell
let userPostRef = self.databaseRef.child("posts")
userPostRef.observeEventType(.ChildAdded, withBlock: {(snapshot) in
if let postAdd = snapshot.value as? NSDictionary{
let myPost = Post(data: postAdd)
self.posts.insert(myPost, atIndex:0)
cell.usernameLabel.text = self.posts[indexPath.row].username
cell.postText.text = self.posts[indexPath.row].postText
cell.timeLabel.text = self.posts[indexPath.row].time
let url = snapshot.value?["postPhoto"] as! String
let userPhotoUrl = snapshot.value?["userPhoto"] as! String
FIRStorage.storage().referenceForURL(url).dataWithMaxSize(10 * 1024 * 1024, completion: { (data, error) in
let postPhoto = UIImage(data: data!)
cell.postPhoto.image = postPhoto
FIRStorage.storage().referenceForURL(userPhotoUrl).dataWithMaxSize(10 * 1024 * 1024, completion: { (data, error) in
let userPhoto = UIImage(data: data!)
cell.userPhoto.image = userPhoto
})
})
}
})
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
这里最好的做法是在ViewDidLoad方法中填充tableView数据源(posts数组).然后你的tableView没有尝试下拉数据,因为它是刷新的.
此外,由于您要添加.childAdded观察器,您的应用程序将收到有关firebase的任何添加的通知,因此当发生这种情况时,只需将新数据添加到posts数组并刷新tableView.
没有理由不断地从Firebase中提取数据,因为它是静态的,直到它发生变化.因此,加载一次,然后等待这些更改 - 您可能需要考虑添加.childChanged事件(并删除),以防有人更新他们的图片.
来自Firebase 的Firechat应用程序是了解最佳方法的一个很好的资源 - 如果您遵循该设计模式,您可以避免所有网络问题,而不必担心单独的异步调用.
您可以简单地依靠Firebase来照顾自己.
编辑......好吧,虽然这是一个Firechat链接,Obj-C代码似乎丢失了(感谢Firebase.呃)
所以 - 鉴于此,请参阅我对这个问题的回答,因为它具有您需要的代码模式.
| 归档时间: |
|
| 查看次数: |
10571 次 |
| 最近记录: |