Advanced Networking with URLSession

Sep 15 2022 · Swift 5.6, iOS 15, Xcode 13.4.1

Part 2: Authentication, Cookies & App Transport Security

12. Challenge: Print Cookies from a Request

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 11. Work With Cookies Next episode: 13. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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
  }
}