从Firebase提取用户名:展开一个可选值时意外发现nil

时间:2018-07-01 11:46:46

标签: swift firebase firebase-realtime-database

我试图显示将图像发布到homeViewController的用户的用户名,但该用户名显示为nil。我认为我的代码中缺少重要的内容,但不确定是什么?

我收到以下错误:

  

线程1:致命错误:展开包装时意外发现nil   可选值

在HomeViewController的loadPosts()函数中:

self.fetchUser(uid: post.uid!, completed: {

HomeViewController:

class HomeViewController: UIViewController {

    @IBOutlet var popover: UIView!
    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var popoverUsername: UILabel!


    @IBOutlet weak var tableView: UITableView!
    var posts = [Post]()
    var users = [User]()

    var postId: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.estimatedRowHeight = 417
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.dataSource = self

        loadPosts()
        self.popover.layer.cornerRadius = 20


    }
    @IBAction func dismiss_Popover(_ sender: Any) {

//        dismiss(animated: true, completion: nil)
        self.dismiss(animated: true, completion: nil)
//        dismiss(animated: true, completion: nil)
//        popoverPresentationController?.delegate?.popoverPresentationControllerDidDismissPopover?(popoverPresentationController!)

    }

    @IBAction func popoverOpen_TouchUpInside(_ sender: Any) {
    self.view.addSubview(popover)
        popover.center = self.view.center

    }

    func loadPosts() {
        Api.Post.observePosts { (post) in
            self.fetchUser(uid: post.uid!, completed: {
            self.posts.insert(post, at: 0)
            self.tableView.reloadData()
            })
        }
    }

        func fetchUser(uid: String, completed:  @escaping () -> Void ) {
            Api.User.observeUser(withId: uid, completion: {
                user in
                self.users.append(user)
                completed()
            })
        }

    @IBAction func logout_TouchUpInside(_ sender: Any) {
        do {
            try Auth.auth().signOut()
        } catch let logoutError {
            print(logoutError)
        }
        dismiss(animated: true, completion: nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "SiteSegue" {
            let siteVC = segue.destination as! SiteViewController
            let postId = sender as! String
            siteVC.postId = postId

        }
    }
}

extension HomeViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! HomeTableViewCell
        let post = posts[indexPath.row]
        let user = users[indexPath.row]
        cell.user = user
        cell.post = post
        cell.delegate = self
        return cell
    }
}



extension HomeViewController: HomeTableViewCellDelegate {
    func goToSiteVC(postId: String) {
        performSegue(withIdentifier: "SiteSegue", sender: postId)
    }
}

HomeTableViewCell:

class HomeTableViewCell: UITableViewCell {

    @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var siteImageView: UIImageView!
    @IBOutlet weak var siteTitleLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var dateLabel: UILabel!


    var delegate: HomeTableViewCellDelegate?

    var post: Post? {
        didSet {
            updateView()
        }
    }

    var user: User? {
        didSet {
            setupUserInfo()
        }
    }

    func updateView() {
        siteTitleLabel.text = post?.caption
        dateLabel.text = post?.pickerTextField
        }


    func setupUserInfo() {
        usernameLabel.text = user?.username
        if let photoUrlString = user?.profileImageUrl {
            let photoUrl = URL(string: photoUrlString)
            profileImageView.sd_setImage(with: photoUrl, placeholderImage: UIImage(named: "placeholderImg"))

        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        usernameLabel.text = ""
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.siteImageView_TouchUpInside))
        siteImageView.addGestureRecognizer(tapGesture)
        siteImageView.isUserInteractionEnabled = true
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @objc func siteImageView_TouchUpInside() {
        if let id = post?.id {
            delegate?.goToSiteVC(postId: id)
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        profileImageView.image = UIImage(named: "placeholderImg")
    }

}

UserApi:

class UserApi {
    var REF_USERS = Database.database().reference().child("users")

    func observeUser(withId uid: String, completion: @escaping (User) -> Void) {
        REF_USERS.child(uid).observeSingleEvent(of: .value, with: {
            snapshot in
            if let dict = snapshot.value as? [String: Any] {
                let user = User.transformUser(dict: dict, key: snapshot.key)
                completion(user)
            }
        })
    }

}

0 个答案:

没有答案