Ch.20 Bronze: Printing the Response Information

sun·2022년 2월 9일
0

# dataTask 의 response 찍어보기!

  • dataTask 가 종료되면 URLResponse 를 받아오는 데 http 통신을 한 경우에는 이를 서브클래싱한 HTTPURLResponse 를 받게 된다. 여기에는 다양한 정보들이 포함되는 데, 과제에서 print문으로 확인해보라는 status 코드와 header field 도 그중 일부! 디버깅할 때 유용하게 사용할 수 있고, status 코드를 사용해서 에러 처리도 더 세분화할 수 있다.
  • HTTPURLRequest 로 다운캐스팅해서 아까 얘기한 프로퍼티들을 확인해보면 끝!
class PhotoStore {
    private let session: URLSession = {
        let config = URLSessionConfiguration.default
        return URLSession(configuration: config)
    }()
    
    func fetchInterestingPhotos(completion: @escaping (Result<[Photo], Error>) -> Void) {
        let url = FlickrAPI.interestingPhotosURL
        let request = URLRequest(url: url)
        let task = session.dataTask(with: request) { data, response, error in
            // 바 로 여 기
            let httpURLResponse = response as! HTTPURLResponse
            print(httpURLResponse.statusCode)
            print(httpURLResponse.allHeaderFields)
            
            let result = self.processPhotosRequest(data: data, error: error)
            OperationQueue.main.addOperation {
                completion(result)
            }
        }
        task.resume()
    }
}
profile
☀️

0개의 댓글