Ch.20 Silver: Fetch Recent Photos from Flickr

sun·2022년 2월 9일
0

# 최근 사진을 불러오는 end point 추가하기

  • Flickr 에서 interesting photos 외에 recent photos 도 불러올 수 있도록 하는 게 과제!
    • 눈 사진이 interesting photos 를 불러온 거고 흑백 숲 사진이 recent photos 에서 불러온 것..! 좀 맘에 드는 사진으로 gif 만들고 싶어서 포스팅 쓰는 내내 n트 했는데 이것도 맘에 완전 드는 건 아니지만 얼굴(초상권 걱정...), 곤충, 에러창 사진을 겪고 나니 선녀같아서 정착했다...


# 코드 확장성 높이기

  • json 포맷이 동일해서 url 만 갈아끼면 데이터 파싱 등에 있어서는 기존 코드를 그대로 사용할 수 있었고, url 도 endpoint 만 교체하면 됐다. 따라서 메서드와 프로퍼티들을 따로 분리하는 게 불필요하다고 생각돼서 recentPhotos 엔드 포인트를 추가한 다음, 기존에 interestingPhotos 가 붙은 모든 메서드와 프로퍼티의 이름을 바꾸고, endpoint 를 받아서 사용하도록 함으로써 기존 로직을 거의 그대로 활용했다.
enum EndPoint: String {
    case interestingPhotos = "flickr.interestingness.getList"
    case recentPhotos = "flickr.photos.getRecent"
}

struct FlickrAPI {
    // 기존에 프로퍼티에서 메서드로 변경 
    // 이외에는 변경사항 없음
    static func URL(for endPoint: EndPoint) -> URL {
        FlickrAPI.flickrURL(endPoint: endPoint, parameters: ["extras": "url_z,date_taken"])
    }
}

class PhotoStore {
    // endPoint 인자를 추가해서 url 생성에 사용
    // 이외에는 변경사항 없음
    func fetchPhotos(_ endPoint: EndPoint, completion: @escaping (Result<[Photo], Error>) -> Void) {
        let url = FlickrAPI.URL(for: endPoint)
        let request = URLRequest(url: url)
        let task = session.dataTask(with: request) { data, response, error in
            let result = self.processPhotosRequest(data: data, error: error)
            OperationQueue.main.addOperation {
                completion(result)
            }
        }
        task.resume()
    }

  • 그리고 EndPoint enum 에 randomElement() 메서드를 추가해서 PhotosViewController 에서 store.fetchPhotos(_:) 메서드를 호출할 때, 매번 랜덤으로 end point 를 인자로 보낼 수 있도록 했다!
enum EndPoint: String {
    case interestingPhotos = "flickr.interestingness.getList"
    case recentPhotos = "flickr.photos.getRecent"
    
    private static var allCases: [EndPoint] {
        [.interestingPhotos, .recentPhotos]
    }
    
    static func randomElement() -> EndPoint {
        allCases.randomElement()!
    }
}

class PhotosViewController: UIViewController {
    ...
    var store: PhotoStore!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        store.fetchPhotos(EndPoint.randomElement()) { photoResults in
            switch photoResults {
            case let .success(photos):
                print("Successfully found \(photos.count) photos.")
                if let firstPhoto = photos.first {
                    self.updateImageView(for: firstPhoto)
                }
            case let .failure(error):
                print("Error fetching interesting photos: \(error)")
            }
        }
    }
}
profile
☀️

0개의 댓글