datasource pattern

godo·2022년 10월 29일
0

적용 받을 뷰

프로토콜

protocol ImageInfoViewDatasource: AnyObject {
    func fetchData(_ infoView: ImageInfoView) -> Album?
}

설정

weak var datasource: ImageInfoViewDatasource?

적용

private func configure() {
    guard let model = datasource?.fetchData(self) else {return}
    self.titleLabel.text = model.title
        
    guard let url = URL(string: model.url) else {return}
        
    let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
         guard let data = data, error == nil else {
             return
         }
            
         DispatchQueue.main.async {
             self?.imageView.image = UIImage(data: data)
         }

    }
    task.resume()
}
public func reloadData() {
   configure()
}

실행 할 뷰 컨트롤러

datasource 적용

infoView.datasource = self

모델 설정

private var model: Album?

fetch 하기

func fetchData() {
     guard let url = URL(string: "https://jsonplaceholder.typicode.com/photos/1") else {return}
        let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
            
        guard let data = data,
        error == nil else {
             return
        }
            
        do {
            let data = try JSONDecoder().decode(Album.self, from: data)
            self?.model = data
        }
        catch {
             print(error)
        }
            
        DispatchQueue.main.async {
            self?.infoView.reloadData()
        }
            
     }
     task.resume()
 }

딜리게이트

extension ViewController: ImageInfoViewDatasource {
    
    func fetchData(_ infoView: ImageInfoView) -> Album? {
        return self.model
    }
}

git : https://github.com/godo129/datasourcePattern_Swift

profile
☀️☀️☀️

0개의 댓글