Advanced Networking with URLSession

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

Part 2: Authentication, Cookies & App Transport Security

11. Work With Cookies

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: 10. Learn App Transport Security Next episode: 12. Challenge: Print Cookies from a Request

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.

Notes: 11. Work With Cookies

When setting up the cookieProperties dictionary, the following line is also required in order for the initializer to return a non-nil value:

cookieProperties[.path] = cookie.path

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

A cookie is a small text file generated by a server to identify a user on subsequent requests.

private func getCookiesTapped() async {
  func setCookies(name: String? = nil, value: String? = nil) {
    Task { @MainActor in
      cookieName = name ?? "N/A"
      cookieValue = value ?? "N/A"
    }
  }
}
guard let url = URL(string: "https://apple.com") else {
  setCookies()
  
  return
}
do {

} catch {
  setCookies()
}
let (_, response) = try await URLSession.shared.data(from: url)     
guard let httpResponse = response as? HTTPURLResponse,
      let fields = httpResponse.allHeaderFields as? [String: String],
      let cookie = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url).first
else {
  setCookies()
    
  return
}
setCookies(name: cookie.name, value: cookie.value)
var cookieProperties: [HTTPCookiePropertyKey: Any] = [:]
cookieProperties[.name] = cookie.name
cookieProperties[.value] = cookie.value
cookieProperties[.domain] = cookie.domain
  
if let myCookie = HTTPCookie(properties: cookieProperties) {
  HTTPCookieStorage.shared.setCookie(myCookie)
  HTTPCookieStorage.shared.deleteCookie(cookie)
}