来自 New Firebase 的扩展问题 检索数据并放在 tableView (Swift)
通过将 Firebase 代码移动到 viewDidLoad,Post 的所有文本部分都可以当前显示。但是我还是不能把图片放到tableView上。我检查了图像检索并且它是成功的,我想我从 Firebase 检索的图像不在 post 数组中。
这是我的修复代码:
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()
let userPostRef = self.databaseRef.child("posts")
userPostRef.queryOrderedByChild("time").observeEventType(.ChildAdded, withBlock: {(snapshot) in
if let postAdd = snapshot.value as? NSDictionary{
let url = snapshot.value?["postPhoto"] as! String
let userPhotoUrl = snapshot.value?["userPhoto"] as! String
let myPost = Post(data: postAdd)
FIRStorage.storage().referenceForURL(url).dataWithMaxSize(10 * 1024 * 1024, completion: { (data, error) in
let postPhoto = UIImage(data: data!)
})
FIRStorage.storage().referenceForURL(userPhotoUrl).dataWithMaxSize(10 * 1024 * 1024, completion: { (data, error) in
let userPhoto = UIImage(data: data!)
})
self.posts.insert(myPost, atIndex: 0)
self.tableView.reloadData()
}
})
}
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 {
return posts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "postCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)as! timelineTableViewCell
//Dispatch the main thread here
dispatch_async(dispatch_get_main_queue()) {
cell.usernameLabel.text = self.posts[indexPath.row].username
cell.postText.text = self.posts[indexPath.row].postText
cell.timeLabel.text = self.posts[indexPath.row].time
cell.postPhoto.image = self.posts[indexPath.row].postPhoto
cell.userPhoto.image = self.posts[indexPath.row].userPhoto
}
return cell
}
}
我的 Post 结构希望它可能会有所帮助!
struct Post {
var username: String?
var postText: String?
var time: String?
var userPhoto: UIImage?
var postPhoto: UIImage?
var url: String?
var userPhotoUrl:String?
init(data: NSDictionary) {
username = data["username"] as? String
postText = data["postText"] as? String
time = data["time"]as? String
userPhoto = data["userPhoto"] as? UIImage
postPhoto = data["postPhoto"] as? UIImage
url = data["postPhoto"] as? String
userPhotoUrl = data["userPhoto"] as? String
}
}
希望能得到一些建议!