我正在使用Swift 3
我有像twitter这样的社交网络,我试图回顾用户的以下列表,但我遇到了一些麻烦,我的想法是让他们这样我可以使用它们然后做一个for循环并检索帖子或推文,所以这样的事情
self.databaseRef.child("following").child((self.loggedInUser?.uid)!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
for child in snapshot.children {
self.databaseRef.child("Jalas").child((child as AnyObject).key!).observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
if (snapshot.value as? NSDictionary != nil)
{
self.Jalas.append(snapshot.value as! NSDictionary)
}
}){(error) in
print(error.localizedDescription)
}
}
self.homeTableView.beginUpdates()
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
self.homeTableView.endUpdates()
self.aivLoading.stopAnimating()
}
并且我在返回self.Jalas.count的部分行数,但这没有任何作用。它给我一个错误。
“尝试将第0行插入第0部分,但更新后第0部分只有0行”
这是我的数据库。
Jalas =帖子
{
"Jalas" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"-KbHUnL-RveUQa3MPSWp" : {
"latitud" : "21.111401000574",
"longitud" : "-89.6112191677094",
"text" : "Fiesta en la Anahuac!!! ",
"timestamp" : "1485295269.30773",
"ubicacionN" : "Universidad Anáhuac Mayab"
},
"-KbI1azr6uFel-5uTZOD" : {
"latitud" : "Optional(21.018988764483463)",
"longitud" : "Optional(-89.614319546492695)",
"text" : "Hola chicos",
"timestamp" : "1485304393.77929",
"ubicacionN" : "Calle 53-A 341"
},
"-KbNQWxjQhc0Ce_ZQbq9" : {
"latitud" : "Optional(21.019219877217914)",
"longitud" : "Optional(-89.614173537203683)",
"text" : "Hola",
"timestamp" : "1485394812.83039",
"ubicacionN" : "Calle 53 341"
}
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"-KbQOWfUnzY1JiS61J6-" : {
"latitud" : "Optional(21.111502615883129)",
"longitud" : "Optional(-89.611767497121221)",
"text" : "Hola chicos!",
"timestamp" : "1485444619.10931",
"ubicacionN" : "Carretera Mérida-Progreso 96"
}
}
},
"follower" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"mt0fzirhMhazIcy90MRWuRpTfmE2" : true
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : true
}
},
"following" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"mt0fzirhMhazIcy90MRWuRpTfmE2" : true
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : true
}
},
"handles" : {
"jcadmin" : "mt0fzirhMhazIcy90MRWuRpTfmE2",
"jcbest" : "dEXaVLDOSPfJa3zTyUNqAEtVuMR2"
},
"user_profiles" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"about" : "Hola Mundo",
"handle" : "jcbest",
"name" : "Juan Carlos Estevez Rodriguez",
"profile_pic" : "https://firebasestorage.googleapis.com/v0/b/jalo-267da.appspot.com/o/user_profiles%2FOptional(%22dEXaVLDOSPfJa3zTyUNqAEtVuMR2%22)%2Fprofile_pic?alt=media&token=bfc3c516-7849-472c-b7cd-9668965a5dbe"
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"about" : "Hola chicos",
"handle" : "jcadmin",
"name" : "Juan Carlos",
"profile_pic" : "https://firebasestorage.googleapis.com/v0/b/jalo-267da.appspot.com/o/user_profiles%2FOptional(%22mt0fzirhMhazIcy90MRWuRpTfmE2%22)%2Fprofile_pic?alt=media&token=b741b6c1-0bc5-446d-a1e5-159b21e770d2"
}
}
}
这是我的全部代码。
//
// HomeViewController.swift
// Twitter Clone
//
// Created by Juan Carlos Estevez on 15/12/16.
// Copyright © 2016 JC&C. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
import SDWebImage
import ReadMoreTextView
class HomeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {
var databaseRef = FIRDatabase.database().reference()
var loggedInUser:AnyObject?
var loggedInUserData:NSDictionary?
var listFollowing = [NSDictionary?]()
var listFollowers = [NSDictionary?]()//store all the followers
@IBOutlet weak var aivLoading: UIActivityIndicatorView!
@IBOutlet weak var homeTableView: UITableView!
var defaultImageViewHeightConstraint:CGFloat = 77.0
var Jalas = [NSDictionary]()
override func viewDidLoad() {
super.viewDidLoad()
self.homeTableView.separatorStyle = .none
//self.homeTableView.backgroundView?.backgroundColor = UIColor.init(red: 247, green: 247, blue: 247, alpha: 1)
UITabBar.appearance().tintColor = UIColor.orange
navigationController?.navigationBar.barTintColor = UIColor.orange
Evento.sharedInstance.titulo = ""
Evento.sharedInstance.UbicacionN = nil
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("following").child((self.loggedInUser?.uid)!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
for child in snapshot.children {
self.databaseRef.child("Jalas").child((child as AnyObject).key!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
//if (snapshot.value as? NSDictionary != nil)
//{
self.Jalas.append(snapshot.value as! NSDictionary)
//}
}
}
//self.homeTableView.beginUpdates()
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
//self.homeTableView.endUpdates()
self.aivLoading.stopAnimating()
}
/*
//get the logged in users details
self.databaseRef.child("user_profiles").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
//store the logged in users details into the variable
self.logdInUserData = snapshot.value as? NSDictionary
// print(self.loggedInUserData)
//get all the Jalas that are made by the user
self.databaseRef.child("Jalas").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
//self.Jalas.append(snapshot.value as! NSDictionary)
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
self.aivLoading.stopAnimating()
}){(error) in
print(error.localizedDescription)
}
}
*/
//when the user has no posts, stop animating the aiv after 5 seconds
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(stopAnimating), userInfo: nil, repeats: false)
self.homeTableView.rowHeight = UITableViewAutomaticDimension
self.homeTableView.estimatedRowHeight = 140
/*
self.databaseRef.child("following").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot) in
let snapshot = snapshot.value as? NSDictionary
self.listFollowing.append(snapshot)
print(self.listFollowing)
}) { (error) in
print(error.localizedDescription)
}
self.databaseRef.child("followers").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot) in
let snapshot = snapshot.value as? NSDictionary
self.listFollowers.append(snapshot)
print(self.listFollowers)
}) { (error) in
print(error.localizedDescription)
}
*/
}
@IBAction func NewJalo(_ sender: Any) {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let welcomeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "new")
self.present(welcomeViewController, animated: true, completion: nil)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.orange
return true
}
open func stopAnimating()
{
self.aivLoading.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.Jalas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.separatorStyle = .none
var ubicacion = ""
let cell: HomeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! HomeViewTableViewCell
cell.contentView.backgroundColor = UIColor.clear
let JaloPost = Jalas[(self.Jalas.count-1) - (indexPath.row)]["text"] as! String
var HG = 105
let CHAR = JaloPost.characters.count
if (CHAR > 30)
{
let CH = ((CHAR/30) * 15)
HG += CH
}
if(Jalas[(self.Jalas.count-1) - (indexPath.row)]["picture"] != nil)
{
HG += 77
}
let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: Int(self.view.frame.size.width - 20), height: HG))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 2.0
whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
whiteRoundedView.layer.shadowOpacity = 0.2
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
let imageTap = UITapGestureRecognizer(target: self, action: #selector(self.didTapMediaInTweet(_:)))
cell.tweetImage.addGestureRecognizer(imageTap)
if(Jalas[(self.Jalas.count-1) - (indexPath.row)]["ubicacionN"] != nil)
{
ubicacion = (Jalas[(self.Jalas.count-1) - (indexPath.row)]["ubicacionN"] as? String)!
}
if(Jalas[(self.Jalas.count-1) - (indexPath.row)]["picture"] != nil)
{
cell.tweetImage.isHidden = false
cell.imageViewHeightConstraint.constant = defaultImageViewHeightConstraint
let picture = Jalas[(self.Jalas.count-1) - (indexPath.row)]["picture"] as! String
let url = URL(string:picture)
cell.tweetImage.layer.cornerRadius = 10
cell.tweetImage.layer.borderWidth = 3
cell.tweetImage.layer.borderColor = UIColor.clear.cgColor
cell.tweetImage!.sd_setImage(with: url, placeholderImage: UIImage(named:"twitter")!)
}
else
{
cell.tweetImage.isHidden = true
cell.imageViewHeightConstraint.constant = 0
}
if (self.loggedInUserData!["profile_pic"] == nil)
{
cell.configure(nil,name:self.loggedInUserData!["name"] as! String,handle:self.loggedInUserData!["handle"] as! String,tweet:JaloPost, ubi: ubicacion)
}else
{
cell.configure(self.loggedInUserData!["profile_pic"]! as? String,name:self.loggedInUserData!["name"] as! String,handle:self.loggedInUserData!["handle"] as! String,tweet:JaloPost, ubi: ubicacion)
}
return cell
}
func didTapMediaInTweet(_ sender:UITapGestureRecognizer)
{
let imageView = sender.view as! UIImageView
let newImageView = UIImageView(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = UIColor.black
newImageView.contentMode = .scaleAspectFit
newImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
func dismissFullScreenImage(_ sender:UITapGestureRecognizer)
{
sender.view?.removeFromSuperview()
}
/*
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "findUserSegue")
{
var showFollowingTableViewController = segue.destination as! FollowUsersTableViewController
showFollowingTableViewController.loggedInUser = self.loggedInUser as? FIRUser
// showFollowingTableViewController.followData = self.followData
}
else if(segue.identifier == "showFollowersTableViewController")
{
var showFollowersTableViewController = segue.destination as! ShowFollowersTableViewController
showFollowersTableViewController.user = self.loggedInUser as? FIRUser
}
}
*/
}
这是我的Table View Cell代码。
//
// HomeViewTableViewCell.swift
// Jalo
//
// Created by Juan Carlos Estevez Rodriguez on 24/08/16.
// Copyright © 2016 JC&C. All rights reserved.
//
import UIKit
open class HomeViewTableViewCell: UITableViewCell {
@IBOutlet weak var profilePic: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var handle: UILabel!
@IBOutlet weak var tweet: UITextView!
@IBOutlet weak var tweetImage: UIImageView!
@IBOutlet weak var ubic: UILabel!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
override open func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
open func configure(_ profilePic:String?,name:String,handle:String,tweet:String, ubi:String)
{
self.tweet.text = tweet
self.handle.text = "@"+handle
self.name.text = name
self.ubic.text = ubi
if((profilePic) != nil)
{
let imageData = try? Data(contentsOf: URL(string:profilePic!)!)
self.profilePic.image = UIImage(data:imageData!)
}
else
{
self.profilePic.image = UIImage(named:"twitter")
}
}
}
答案 0 :(得分:0)
此
self.homeTableView.beginUpdates()
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
self.homeTableView.endUpdates()
细分是最有可能导致问题的原因。在您编辑问题并添加确切错误之前,我们不确定。
在UITableView中使用.insertRows()
时,您需要确保numberOfRows inSection
方法中的计数也相应更改。你在这里只是委托方法返回的行数与实际行数之间的不匹配。确保在使用.insertRows()
时,在委托方法中返回新的预期行数!