[iOS] Firebase 연동해서 친구목록 나타내기

정환우·2021년 2월 1일
0

iOS

목록 보기
16/24

로그인하면 이렇게 Firebase 서버에 있는 친구 목록이 뜨게 하는 것인데, 설명도 부족해서 코드 하나하나 내가 해석해보고, 모르는거 찾아보고 하느라 강의 시간은 16분인데 실제 이해하는 시간은 2시간 정도 걸리는 듯하다. 그리고 여기서는 코드로 테이블 뷰, 셀, 이미지 뷰를 다만드는데, 나는 테이블 뷰는 그냥 오토레이아웃 적용해서 끌어다 쓰는 방식으로 했다. 이렇게 해야 조금 더 이해하는 거 같고 내가 아는 것도 적용하는 느낌이 들어서..?

코드를 분석하다보니 DispatchQueue가 굉장히 많이 나오는데, 이게 뭔지 아직까지 이해가 잘 되질 않는다.

GCD(Grand Central Dispatch)라는 C를 기반으로 하는 저수준의 API라는데, 멀티스레딩을 위한 것이라고 한다.아직까지 잘 이해가 안가니 계속 찾아보면서 꼭 이해를 해서 아예 따로 글을 하나 작성하려고 한다.

완성 코드

//
//  MainViewController.swift

import UIKit
import SnapKit
import Firebase

class PeopleViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {

    
    @IBOutlet weak var tableView: UITableView!{
        didSet{
            tableView.delegate = self
            tableView.dataSource = self
            tableView.separatorStyle = .none
        }
    }
    var array : [UserModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        
        Database.database().reference().child("users").observe(DataEventType.value, with: { (snapshot) in
            
            
            self.array.removeAll()
            
            for child in snapshot.children{
                let fchild = child as! DataSnapshot
                let userModel = UserModel()
                
                userModel.setValuesForKeys(fchild.value as! [String : Any])
                self.array.append(userModel)
                
            }
            
            DispatchQueue.main.async {
                self.tableView.reloadData();
            }
        })
        
        
        
        

        // Do any additional setup after loading the view.
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for :indexPath)
        
        
        let imageview = UIImageView()
        cell.addSubview(imageview)
        imageview.snp.makeConstraints { (m) in
            m.centerY.equalTo(cell)
            m.left.equalTo(cell)
            m.height.width.equalTo(50)
        }
        
        
        URLSession.shared.dataTask(with: URL(string: array[indexPath.row].profileImageUrl!)!) { (data, response, err) in
            
            
            DispatchQueue.main.async {
                imageview.image = UIImage(data: data!)
                imageview.layer.cornerRadius = imageview.frame.size.width/2
                imageview.clipsToBounds = true
            }
            
        }.resume()
        
        let label = UILabel()
        cell.addSubview(label)
        label.snp.makeConstraints { (m) in
            m.centerY.equalTo(cell)
            m.left.equalTo(imageview.snp.right).offset(30)
        }
        
        label.text = array[indexPath.row].userName
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

전에 수강한 오토레이아웃 강의 내용이 생각보다 많이 들어있어서 이해도 가고 활용도 좀 하는듯 하다. Database같은 건 Firebase docs에 가면 다 찾을 수 있다. Snpashot.children 이 부분이 살짝 이해가 안가긴 하는데, 그러려니 하는중...

내가 이걸 혼자서 백지 상태에서 만들 수 있으려나 모르겠다.ㅋㅋ 예전에 유니티 다룰때도 이런식으로 하다가 결국 해냈으니 해낼 수 있을거라 믿는다!

profile
Hongik CE

0개의 댓글