Solution for Ch 20 Bronze, Silver Challenge in Xcode 9.3


#1
//  PhotosViewController.swift

class PhotosViewController: UIViewController {
...
  override func viewDidLoad() {
    super.viewDidLoad()

    let segmentedControl = UISegmentedControl(items: ["Interesting", "Recent"])
    segmentedControl.addTarget(self, action: #selector(selectMethod(_:)), for: .valueChanged)
    navigationItem.titleView = segmentedControl
  }

  @objc func selectMethod(_ sender: UISegmentedControl) {
    sender.isEnabled = false
    let method = sender.selectedSegmentIndex == 1 ? Method.recentPhotos : .interestingPhotos

//    store.fetchInterestingPhotos { (photosResult) -> Void in
    store.fetchPhotos(for: method) { (photosResult) -> Void in
      DispatchQueue.main.async {
        sender.isEnabled = true
      }
      switch photosResult {
      case let .success(photos):
        print("Successfully found \(photos.count) photos.")
        if let firstPhoto = photos.first {
          DispatchQueue.main.async {
            self.updateImageView(for: firstPhoto)
          }
        }
      case let .failure(error):
        print("Error fetching photos: \(error)")
      }
    }
  }
}
//  FlickrAPI.swift

enum Method: String {
  case interestingPhotos = "flickr.interestingness.getList"
  case recentPhotos = "flickr.photos.getRecent"
}

struct FlickrAPI {
//  static var interestingPhotosURL: URL {
//    return flickrURL(method: .interestingPhotos, parameters: ["extras": "url_h,date_taken"])
//  }

  static func photosURL(for method: Method) -> URL {
    return FlickrAPI.flickrURL(method: method, parameters: ["extras": "url_h,date_taken"])
  }
...
}
//  PhotoStore.swift

class PhotoStore {
...
//  func fetchInterestingPhotos(completion: @escaping (PhotosResult) -> Void) {
  func fetchPhotos(for method: Method, completion: @escaping (PhotosResult) -> Void) {
//    let url = FlickrAPI.interestingPhotosURL
    let url = FlickrAPI.photosURL(for: method)
    
    let request = URLRequest(url: url)
    let task = session.dataTask(with: request) { (data, response, error) in
      // Bronze Challenge
      self.printHTTPHeader(for: response)

      let result = self.processPhotosRequest(data: data, error: error)
        completion(result)
    }
    task.resume()
  }

  // MARK: - Bronze Challenge: Printing the Response Information
  func printHTTPHeader(for response: URLResponse?) {
    guard let aHTTPURLResponse = response as? HTTPURLResponse  else {
      return
    }

    let statusCode = aHTTPURLResponse.statusCode
    print("HTTP Status Code: \(statusCode)")
    print("Message: \(HTTPURLResponse.localizedString(forStatusCode: statusCode))")
    print("All HTTP Header Fields:")
    for (key, value) in aHTTPURLResponse.allHeaderFields {
      print("\(key) : \(value)")
    }
  }
}