Bronze Challenge Solution Ch. 20 - Printing the Response Information


#1

In PhotoStore.swift

func fetchInterestingPhotos(completion: @escaping (PhotosResult) -> Void) {

    let url = FlickrAPI.interestingPhotosURL
    let request = URLRequest(url: url)
    let task = session.dataTask(with: request) {
        (data, response, error) -> Void in
        
        let httpResponse = response as? HTTPURLResponse
        
        if let statusCode = httpResponse?.statusCode {
            print("HTTP Status Code: \(statusCode)")
        }
        
        if let headerFields = httpResponse?.allHeaderFields {
            for (key, value) in headerFields {
                print("\(key): \(value)")
            }
            print("")
        }
        
        let result = self.processPhotosRequest(data: data, error: error)
        OperationQueue.main.addOperation {
            completion(result)
        }
    }
    task.resume()
}

func fetchImage(for photo: Photo, completion: @escaping (ImageResult) -> Void) {

    let photoURL = photo.remoteURL
    let request = URLRequest(url: photoURL)
    
    let task = session.dataTask(with: request) {
        (data, response, error) -> Void in
        
        let httpResponse = response as? HTTPURLResponse
        
        if let statusCode = httpResponse?.statusCode {
            print("HTTP Status Code: \(statusCode)")
        }
        
        if let headerFields = httpResponse?.allHeaderFields {
            for (key, value) in headerFields {
                print("\(key): \(value)")
            }
            print("")
        }
        
        let result = self.processImageRequest(data: data, error: error)
        OperationQueue.main.addOperation {
            completion(result)
        }
    }
    task.resume()
}