Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Challenge: Print Cookies from a Request

This video was last updated on Sep 15 2022

In this challenge, you’ll use the knowledge gained in the previous episode to print not just one, but all of the cookies available to you from your request.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Working with cookies is pretty important, so it’s time to give you a good old fashioned cookie challenge.

guard let url = URL(string: "https://google.com”) else {
  setDescription()
  
  return
}
do {
  let (_, response) = try await URLSession.shared.data(from: url)
  
} catch {
  setDescription()
}
guard let httpResponse = response as? HTTPURLResponse,
      let fields = httpResponse.allHeaderFields as? [String: String]
else {
  setDescription()
    
  return
}
let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
  
setDescription(for: cookies)
func setDescription(for cookies: [HTTPCookie]? = nil) {
  Task { @MainActor in
    guard let cookies = cookies, !cookies.isEmpty else {
      description = "Cookies: N/A"
          
      return
    }
        
    var descriptionString = ""
        
    for cookie in cookies {
      descriptionString += "\(cookie.name): \(cookie.value)\n"
    }
        
    description = descriptionString
  }
}

Reviews

Comments