LoginSignup
2
2

More than 5 years have passed since last update.

お気に入り登録した記事を閲覧できる画面の実装

Posted at

シンプルです。

import UIKit
import Firebase
import FirebaseAuth
import SVProgressHUD

class ClipViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //お気に入り登録された記事情報を格納する配列を用意。ArticleQueryDataは記事のModel。
    var likesArray: [ArticleQueryData] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(R.nib.listCell)
        tableView.estimatedRowHeight = 200
        SVProgressHUD.show()
    }

    override func viewWillAppear(_ animated: Bool) {
    //navigationBarの設定など。省略
    }

    override func viewWillDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
    }

    @IBOutlet weak var tableView: UITableView!

    func reloadFavoriteData() {
        if let user = Auth.auth().currentUser {
            let uid = user.uid
            let ref = Firestore.firestore().collection("articleData")
            ref.addSnapshotListener { querySnapshot, err in
                if let err = err {
                    print("Error fetching documents: \(err)")
                } else {
                    self.likesArray = []
                    for document in querySnapshot!.documents {
                        let articleData = ArticleQueryData(snapshot: document, myId: uid)
                        self.likesArray.insert(articleData, at: 0)
                    }

                    //記事情報には"likes":["UserID","UserID","UserID"]のように、お気に入り登録したユーザーのIDが登録されている。filterを使って、"likes"がユーザーのID(uid)を含む記事を抽出している。
                    self.likesArray = self.likesArray.filter { $0.likes.contains(uid) }

                    //これはなくても良いかも?"いいね"ボタンを押した時にoffsetがずれる時のための気休め。
                    let before = self.tableView.contentOffset.y
                    self.tableView.reloadData()
                    let after = self.tableView.contentOffset.y

                    if before > after {
                        self.tableView.contentOffset.y = before
                    }

                    SVProgressHUD.dismiss()

                }
            }
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return likesArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: R.nib.listCell, for:indexPath)  else { return UITableViewCell()}
        cell.setCellInfo(articleData: likesArray[indexPath.row])
        cell.clipButton.addTarget(self, action: #selector(handleButton(sender:event:)), for: UIControl.Event.touchUpInside)
        cell.selectionStyle = .none //ハイライトを消す
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectCellViewModel = likesArray[indexPath.row]
        fromClipArticleToSummary(giveCellViewModel: selectCellViewModel)
    }

    func fromClipArticleToSummary(giveCellViewModel:ArticleQueryData) {
        //省略。navigationControllerで値を渡しながら遷移する処理
    }


    //減らしていくだけの処理なので、他と少し異なることに注意。そのままコピペするとエラーになる。
    @objc func handleButton(sender: UIButton, event:UIEvent) {
        // タップされたセルのインデックスを求める
        let touch = event.allTouches?.first
        let point = touch!.location(in: self.tableView)
        let indexPath = tableView.indexPathForRow(at: point)

        // 配列からタップされたインデックスのデータを取り出す
        let likeData = likesArray[indexPath!.row]

        // Firebaseに保存するデータの準備
        if let uid = Auth.auth().currentUser?.uid {
            var index = -1
            for likeId in likeData.likes {
                if likeId == uid {
                    // 削除するためにインデックスを保持しておく
                    index = likeData.likes.index(of: likeId)!
                    break
                }
            }
            likeData.likes.remove(at: index)

            let likeRef = Firestore.firestore().collection("articleData").document(likeData.id!)
            let likes = ["likes": likeData.likes]

            likeRef.updateData(likes){ err in
                if let err = err {
                    print("Error adding document: \(err)")
                } else {
                    print("Document successfully written!")
                }   
            }
        }        
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2