포스트

Final (13)

ManageVC 만들기

유져나, 게시글 관리를 위한 VC를 만드려고한다.

의존성 주입을 나름대로 해서 SceneDelegate에서 VC를 호출하게 했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func switchToGreetingViewController() {
        greetingVC = GreetingViewController(
            appleTapped: { [weak signViewModel] in
                signViewModel?.appleLoginDidTapped()
            },
            googleTapped: { [weak signViewModel] in
                signViewModel?.googleLoginDidTapped(presentViewController: self.greetingVC)},
            hiddenTapped: { 
                self.greetingVC.present(self.manageVC, animated: true)
            },
            viewModel: signViewModel)
        
        window?.rootViewController = greetingVC
    } 

ManageManager 만들기

1
2
3
4
5
6
7
8
func fetchUsers(completion: @escaping ((any Error)?, DataSnapshot?) -> Void) {
        let ref = Database.database().reference()
        ref.child(db_user_users).getData(completion: completion)
    }
    
func fetchUserReviews(completion: @escaping (QuerySnapshot?, (any Error)?) -> Void) {
        reviewCollection.getDocuments(completion: completion)
    }

ViewModel 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
private let manageManager: ManageManager
    
    init(manageManager: ManageManager) {
        self.manageManager = manageManager
    }
    
    var managePublisher = PassthroughSubject<Void, Error>()
    @Published var userReview = [ReviewModel]()
    @Published var userArray = [UserModel]()
    
    func getUsers() {
        manageManager.fetchUsers { [weak self] error, dataSnapshot in
            self?.userArray.removeAll()
            if let error = error {
                self?.managePublisher.send(completion: .failure(error))
            }
            guard let dictionary = dataSnapshot?.value as? [String: [String: Any]] else { return }
            
            for (uid, userDict) in dictionary {
                let email = userDict[db_email] as? String ?? ""
                let nickName = userDict[db_nickName] as? String ?? ""
                let profileImageUrl = userDict[db_profileImageUrl] as? String ?? ""
                let isBlockInt = userDict[db_isBlock] as? Int ?? 0
                let isBlock = isBlockInt != 0
                
                let model = UserModel(uid: uid, email: email, isBlock: isBlock, nickName: nickName, profileImageUrl: profileImageUrl)
                self?.userArray.append(model)
            }
            self?.managePublisher.send(())
        }
    }
    
    func getRevies() {
        manageManager.fetchUserReviews { [weak self] querySnapshot, error in
            self?.userReview.removeAll()
            if let error = error {
                self?.managePublisher.send(completion: .failure(error))
            }
            
            if let snapshotDocuments = querySnapshot?.documents {
                if !snapshotDocuments.isEmpty {
                    for doc in snapshotDocuments {
                        let data = doc.data()
                        guard
                            let uid = data[db_uid] as? String,
                            let title = data[db_title] as? String,
                            let storeName = data[db_storeName] as? String,
                            let storeAddress = data[db_storeAddress] as? String,
                            let content = data[db_content] as? String,
                            let rating = data[db_rating] as? Float,
                            let imageURL = data[db_imageURL] as? [String],
                            let isActive = data[db_isActive] as? Bool,
                            let createdAt = data[db_createdAt] as? Timestamp,
                            let updatedAt = data[db_updatedAt] as? Timestamp
                        else {
                            print("error")
                            return
                        }
                        let reviewData = ReviewModel(uid: uid, title: title, storeAddress: storeAddress, storeName: storeName, content: content, rating: rating, imageURL: imageURL, isActive: isActive, createdAt: createdAt, updatedAt: updatedAt)
                        self?.userReview.append(reviewData)
                        self?.managePublisher.send(())
                    }
                }
            }
        }
    }

여기서 이상하게 안되었던부분이 바로 여기.

1
2
3
4
5
let email = userDict[db_email] as? String ?? ""
let nickName = userDict[db_nickName] as? String ?? ""
let profileImageUrl = userDict[db_profileImageUrl] as? String ?? ""
let isBlockInt = userDict[db_isBlock] as? Int ?? 0
let isBlock = isBlockInt != 0

guard let으로 처음에 했는데 자꾸 else로 빠져나가면서 원하는 데이터를 가져오지 못하는 경우가 생겼다.

그래서 옵셔널 바인딩을 하기로 결정.

VC 디퍼블 데이터 소스 적용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// MARK: - Diffable DataSource
extension ManageViewController {
    func configureDiffableDataSource() {
        tableDatasource = UITableViewDiffableDataSource(tableView: manageView.tableView, cellProvider: { tableView, indexPath, itemIdentifier in
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ManageTableViewCell", for: indexPath) as! ManageTableViewCell
            
            switch itemIdentifier {
            case .user(let users):
                
                cell.titleLabel.text = users.uid
                
                return cell
            case .review(let review):
                print(review)
                cell.titleLabel.text = review.title
                return cell
            }
            
        })
    }
    
    func configureUserSnapshot() {
        var userSnapshot = NSDiffableDataSourceSnapshot<DiffableSectionModel, DiffableSectionItemModel>()
        
        userSnapshot.appendSections([.user])
        let userItems = viewModel.userArray.map { DiffableSectionItemModel.user($0) }
        userSnapshot.appendItems(userItems, toSection: .user)
        
        tableDatasource?.apply(userSnapshot, animatingDifferences: true)
    }
    
    func configureReviewSnapshot() {
        var reviewSnapshot = NSDiffableDataSourceSnapshot<DiffableSectionModel, DiffableSectionItemModel>()

        reviewSnapshot.appendSections([.review])
        let reviewItems = viewModel.userReview.map { DiffableSectionItemModel.review($0) }
        reviewSnapshot.appendItems(reviewItems, toSection: .review)
        
        tableDatasource?.apply(reviewSnapshot, animatingDifferences: true)
    }
    
}

Jun-12-2024 17-57-34

완료.

내일은 실제로 block을 해보는걸로….

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.